Skip to content

Add use of service in dynamic validation group #259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 12, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions core/validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,70 @@ class Book
}
```

Alternatively, you can use a service to retrieve the groups to use:

```php
<?php

// src/AppBundle/Validator/AdminGroupsGenerator.php

namespace AppBundle\Validator;

use AppBundle\Entity\Book;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

final class AdminGroupsGenerator
{
private $authorizationChecker;

public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
}

public function __invoke(Book $book): array
{
return $this->authorizationChecker->isGranted('ROLE_ADMIN', $book) ? ['a', 'b'] : ['a'];
}
}
```

This class selects the groups to apply regarding the role of the current user: if the current user has the `ROLE_ADMIN` role, groups `a` and `b` are returned. In other cases, just `a` is returned.

This class is automatically registered as a service thanks to [the autowiring feature of the Symfony Dependency Injection Component](https://symfony.com/doc/current/service_container/autowiring.html).

Then, configure the entity class to use this service to retrieve validation groups:

```php
<?php

// src/AppBundle/Entity/Book.php

namespace AppBundle\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use AppBundle\Validator\AdminGroupsGenerator;
use Symfony\Component\Validator\Constraints as Assert;

/**
* @ApiResource(attributes={"validation_groups"=AdminGroupsGenerator::class})
*/
class Book
{
/**
* @Assert\NotBlank(groups={"a"})
*/
private $name;

/**
* @Assert\NotNull(groups={"b"})
*/
private $author;

// ...
}
```

Previous chapter: [Serialization Groups and Relations](serialization-groups-and-relations.md)

Next chapter: [Pagination](pagination.md)