src/Security/Voter/InvoiceVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Symfony\Component\Security\Core\User\UserInterface;
  6. use App\Entity\Billing\Invoice;
  7. use Symfony\Component\Security\Core\Security;
  8. class InvoiceVoter extends Voter
  9. {
  10.     private $security;
  11.     public function __construct(Security $security)
  12.     {
  13.         $this->security $security;
  14.     }
  15.     protected function supports(string $attribute$subject): bool
  16.     {
  17.         // replace with your own logic
  18.         // https://symfony.com/doc/current/security/voters.html
  19.         return in_array($attribute, ['INVOICE_EDIT''INVOICE_VIEW'])&& $subject instanceof Invoice;
  20.     }
  21.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  22.     {
  23.         $user $token->getUser();
  24.         // if the user is anonymous, do not grant access
  25.         if (!$user instanceof UserInterface) {
  26.             return false;
  27.         }
  28.         if ($this->security->isGranted('ROLE_ADMIN')) {
  29.             return true;
  30.         }
  31.         // ... (check conditions and return true to grant permission) ...
  32.         switch ($attribute) {
  33.             case 'INVOICE_EDIT':
  34.                 // logic to determine if the user can EDIT
  35.                 // return true or false
  36.                 break;
  37.             case 'INVOICE_VIEW':
  38.                 // logic to determine if the user can VIEW
  39.                 // return true or false
  40.                 return $user === $subject->getOwner();
  41.                 break;
  42.         }
  43.         return false;
  44.     }
  45. }