src/Voter/SupplierCustomerVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Voter;
  3. use App\Entity\Supplier;
  4. use App\Entity\SupplierCustomer;
  5. use App\Entity\User as UserEntity;
  6. use App\Model\SupplierFactory;
  7. use App\Model\User\User;
  8. use Exception;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  11. class SupplierCustomerVoter extends Voter
  12. {
  13.     public const DECLARE_ACCOUNT 'declare_account';
  14.     public const EDIT_ACCOUNT 'edit_account';
  15.     private $user;
  16.     /**
  17.      * @var SupplierFactory
  18.      */
  19.     private $supplierFactory;
  20.     public function __construct(User $userSupplierFactory $supplierFactory)
  21.     {
  22.         $this->user            $user;
  23.         $this->supplierFactory $supplierFactory;
  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::DECLARE_ACCOUNT,
  30.             self::EDIT_ACCOUNT
  31.         ])) {
  32.             return false;
  33.         }
  34.         // only vote on Supplier objects inside this voter
  35.         if (! $subject instanceof SupplierCustomer) {
  36.             return false;
  37.         }
  38.         return true;
  39.     }
  40.     /**
  41.      * @param string $attribute
  42.      * @param Supplier $entity
  43.      *
  44.      * @return bool
  45.      * @throws Exception
  46.      */
  47.     protected function voteOnAttribute($attribute$entityTokenInterface $token): bool
  48.     {
  49.         $userEntity $token->getUser();
  50.         if (! $userEntity instanceof UserEntity) {
  51.             // the user must be logged in; if not, deny access
  52.             return false;
  53.         }
  54.         $this->user->setEntity($userEntity);
  55.         switch ($attribute) {
  56.             case self::DECLARE_ACCOUNT:
  57.                 $supplierEntity $entity->getSupplier();
  58.                 $supplier       $this->supplierFactory->createModel();
  59.                 $supplier->setEntity($supplierEntity);
  60.                 return $supplier->accountCanBeDeclaredBy($this->user);
  61.             case self::EDIT_ACCOUNT:
  62.                 $supplierEntity $entity->getSupplier();
  63.                 $supplier       $this->supplierFactory->createModel();
  64.                 $supplier->setEntity($supplierEntity);
  65.                 return $supplier->accountCanBeModifiedBy($entity$this->user);
  66.         }
  67.         return false;
  68.     }
  69. }