src/Voter/InvoiceVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Voter;
  3. use App\Entity\Invoice;
  4. use App\Entity\User as UserEntity;
  5. use App\Model\InvoiceFactory;
  6. use App\Model\User\User;
  7. use Exception;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  10. class InvoiceVoter extends Voter
  11. {
  12.     public const REMOVE 'remove';
  13.     public const SHOW 'show';
  14.     private $user;
  15.     private $invoiceFactory;
  16.     public function __construct(User $userInvoiceFactory $invoiceFactory)
  17.     {
  18.         $this->user           $user;
  19.         $this->invoiceFactory $invoiceFactory;
  20.     }
  21.     /**
  22.      * @param string $attribute
  23.      * @param mixed $subject
  24.      */
  25.     protected function supports($attribute$subject): bool
  26.     {
  27.         // if the attribute isn't one we support, return false
  28.         if (! in_array($attribute, [
  29.             self::REMOVE,
  30.             self::SHOW
  31.         ])) {
  32.             return false;
  33.         }
  34.         // only vote on Supplier objects inside this voter
  35.         if (! $subject instanceof Invoice) {
  36.             return false;
  37.         }
  38.         return true;
  39.     }
  40.     /**
  41.      * @param string $attribute
  42.      * @param mixed $entity
  43.      * @return bool|void
  44.      * @throws Exception
  45.      */
  46.     protected function voteOnAttribute($attribute$entityTokenInterface $token): bool
  47.     {
  48.         $userEntity $token->getUser();
  49.         if (! $userEntity instanceof UserEntity) {
  50.             // the user must be logged in; if not, deny access
  51.             return false;
  52.         }
  53.         $this->user->setEntity($userEntity);
  54.         $invoice $this->invoiceFactory->createModel($entity);
  55.         switch ($attribute) {
  56.             case self::SHOW:
  57.                 return $this->user->canSeeInvoiceEntity($entity);
  58.             case self::REMOVE:
  59.                 return $invoice->canBeRemovedBy($this->user);
  60.         }
  61.         return false;
  62.     }
  63. }