How to call 2 different symfony voters?

by raven_corwin , in category: PHP Frameworks , 2 months ago

How to call 2 different symfony voters?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 2 months ago

@raven_corwin 

To call two different Symfony voters, you can use the symfony security authorization checker service. Here is an example code snippet to call two different Symfony voters in a controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use SymfonyComponentSecurityCoreAuthorizationAuthorizationCheckerInterface;

class YourController extends AbstractController
{
    private $authorizationChecker;

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

    public function yourAction()
    {
        // Call the first voter
        $isAllowed1 = $this->authorizationChecker->isGranted('YOUR_FIRST_VOTER_ATTRIBUTE');

        // Call the second voter
        $isAllowed2 = $this->authorizationChecker->isGranted('YOUR_SECOND_VOTER_ATTRIBUTE');

        // Do something based on the voter results
        if ($isAllowed1 && $isAllowed2) {
            // Both voters allow the action
            // Your logic here
        } else {
            // At least one voter denies the action
            // Your logic here
        }
    }
}


In this example, 'YOUR_FIRST_VOTER_ATTRIBUTE' and 'YOUR_SECOND_VOTER_ATTRIBUTE' are the attributes defined in your voter classes. Adjust these attributes with the actual attributes you have defined in your voters.