src/Security/Voter/TransactionVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\AbstractCollaborator;
  4. use App\Entity\Reference\ReferenceTransactionStatus;
  5. use App\Entity\Transaction;
  6. use Exception;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\Security;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. class TransactionVoter extends Voter
  12. {
  13.     public const PUT 'PUT';
  14.     public const TRANSACTION_STATUS_ALLOWED_TO_PUT = [
  15.         ReferenceTransactionStatus::REFERENCE_CODE_TRANSACTION_STATUS_PAID,
  16.         ReferenceTransactionStatus::REFERENCE_CODE_TRANSACTION_STATUS_UNDER_COMPROMISE
  17.     ];
  18.     /**
  19.      * @var Security
  20.      */
  21.     private Security $security;
  22.     /**
  23.      * @param Security $security
  24.      */
  25.     public function __construct(Security $security)
  26.     {
  27.         $this->security $security;
  28.     }
  29.     protected function supports(string $attribute$subject): bool
  30.     {
  31.         return $attribute === self::PUT && $subject instanceof Transaction;
  32.     }
  33.     /**
  34.      * @throws Exception
  35.      */
  36.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  37.     {
  38.         /** @var UserInterface $user */
  39.         $user $token->getUser();
  40.         // Deny anonymous users
  41.         if (!$user instanceof UserInterface) {
  42.             return false;
  43.         }
  44.         /** @var Transaction $subject */
  45.         if ($attribute === self::PUT) {
  46.             return (($subject->getOutputAgent() === $user)
  47.                     && in_array($subject->getReferenceTransactionStatus()->getCode(), self::TRANSACTION_STATUS_ALLOWED_TO_PUTtrue))
  48.                 || $this->security->isGranted(
  49.                     AbstractCollaborator::ROLE_MANAGER
  50.                 );
  51.         }
  52.         throw new Exception(sprintf('Unhandled attribute "%s"'$attribute));
  53.     }
  54. }