src/Security/Voter/TransactionVoter.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\Transaction;
  7. use App\Entity\User;
  8. class TransactionVoter extends Voter
  9. {
  10.     public const EDIT 'TRANSACTION_EDIT';
  11.     public const VIEW 'TRANSACTION_VIEW';
  12.     public const REPAIR 'TRANSACTION_REPAIR';
  13.     protected function supports(string $attribute$subject): bool
  14.     {
  15.         // replace with your own logic
  16.         // https://symfony.com/doc/current/security/voters.html
  17.         return in_array($attribute, [self::EDITself::VIEWself::REPAIR]) && $subject instanceof Transaction;
  18.     }
  19.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  20.     {
  21.         $user $token->getUser();
  22.         // if the user is anonymous, do not grant access
  23.         if (!$user instanceof UserInterface) {
  24.             return false;
  25.         }
  26.         // you know $subject is a Transaction object, thanks to `supports()`
  27.         /** @var Transaction $post */
  28.         $transaction $subject;
  29.         // ... (check conditions and return true to grant permission) ...
  30.         switch ($attribute) {
  31.             case self::EDIT:
  32.             case self::REPAIR:
  33.                 return $this->canEdit($transaction$user);
  34.             case self::VIEW:
  35.                 return $this->canEdit($transaction$user);
  36.                 break;
  37.         }
  38.         return false;
  39.     }
  40.     private function canEdit(Transaction $transactionUser $user): bool
  41.     {
  42.         return $user === $transaction->getUser();
  43.     }
  44. }