Reputation: 115
I want to use symfony voters in API PLATFORM. I don't have any problem when I use it on itempsOperations
(GET, PUT, DELETE), but when I use it in collectionOperations
especially in GET (POST works well), I cannot access to the $subject because in GET operation API PLATFORM returns an instance of "ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator" and not entity object.
* @ApiResource(
* collectionOperations={
* "GET"={
* "access_control"="is_granted('GET', object)",
* },
* "POST"={
* "access_control"="is_granted('ADD', object)",
* }
* }
* )
How can I fix this?
Upvotes: 4
Views: 1247
Reputation: 151
I experienced the same problem, dont know if this is a feature or a bug. Since we're basically asking for a set of this recources. And with that in mind a pagination object would make sense, I guess.
A solution arround this issue could be the following:
@\Entity\YourEntity.php
* @ApiResource(
* collectionOperations={
* "GET"={
* "access_control"="is_granted('GET', _api_resource_class)",
* },
* }
* )
@\Security\Voter\YourVoter.php
/**
* Determines if the attribute and subject are supported by this voter.
*
* @param string $attribute An attribute
* @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
*
* @return bool True if the attribute and subject are supported, false otherwise
*/
protected function supports($attribute, $subject)
{
// If the subject is a string check if class exists to support collectionOperations
if(is_string($subject) && class_exists($subject)) {
$subject = new $subject;
}
if(in_array($attribute, ['GET'])
&& $subject instanceof YourEntity) {
return true;
}
Upvotes: 4