Skip to content

Commit 7538a7c

Browse files
pierre-Hmeyerbaptiste
authored andcommitted
Add use of service in dynamic validation group (#259)
1 parent 5556156 commit 7538a7c

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

core/validation.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,70 @@ class Book
9595
}
9696
```
9797

98+
Alternatively, you can use a service to retrieve the groups to use:
99+
100+
```php
101+
<?php
102+
103+
// src/AppBundle/Validator/AdminGroupsGenerator.php
104+
105+
namespace AppBundle\Validator;
106+
107+
use AppBundle\Entity\Book;
108+
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
109+
110+
final class AdminGroupsGenerator
111+
{
112+
private $authorizationChecker;
113+
114+
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
115+
{
116+
$this->authorizationChecker = $authorizationChecker;
117+
}
118+
119+
public function __invoke(Book $book): array
120+
{
121+
return $this->authorizationChecker->isGranted('ROLE_ADMIN', $book) ? ['a', 'b'] : ['a'];
122+
}
123+
}
124+
```
125+
126+
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.
127+
128+
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).
129+
130+
Then, configure the entity class to use this service to retrieve validation groups:
131+
132+
```php
133+
<?php
134+
135+
// src/AppBundle/Entity/Book.php
136+
137+
namespace AppBundle\Entity;
138+
139+
use ApiPlatform\Core\Annotation\ApiResource;
140+
use AppBundle\Validator\AdminGroupsGenerator;
141+
use Symfony\Component\Validator\Constraints as Assert;
142+
143+
/**
144+
* @ApiResource(attributes={"validation_groups"=AdminGroupsGenerator::class})
145+
*/
146+
class Book
147+
{
148+
/**
149+
* @Assert\NotBlank(groups={"a"})
150+
*/
151+
private $name;
152+
153+
/**
154+
* @Assert\NotNull(groups={"b"})
155+
*/
156+
private $author;
157+
158+
// ...
159+
}
160+
```
161+
98162
Previous chapter: [Serialization Groups and Relations](serialization-groups-and-relations.md)
99163

100164
Next chapter: [Pagination](pagination.md)

0 commit comments

Comments
 (0)