src/Voter/ProductVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Voter;
  3. use App\Entity\Product\Product;
  4. use App\Entity\User as UserEntity;
  5. use App\Model\ProductFactory;
  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. use Symfony\Component\Security\Core\Security;
  11. class ProductVoter extends Voter
  12. {
  13.     public const MANAGE_MERCU 'manage_mercu';
  14.     public const MANAGE_GUEST_PRODUCT 'manage_guest_product';
  15.     public const CREATE_GUEST_PRODUCT 'create_guest_product';
  16.     public const READ_GUEST_PRODUCT 'read_guest_product';
  17.     private $user;
  18.     private $productFactory;
  19.     public function __construct(Security $securityUser $userProductFactory $productFactory)
  20.     {
  21.         $this->user           $user;
  22.         $this->productFactory $productFactory;
  23.     }
  24.     protected function supports($attribute$subject): bool
  25.     {
  26.         // if the attribute isn't one we support, return false
  27.         if (!in_array($attribute, [
  28.             self::MANAGE_MERCU,
  29.             self::MANAGE_GUEST_PRODUCT,
  30.             self::READ_GUEST_PRODUCT,
  31.             self::CREATE_GUEST_PRODUCT
  32.         ])) {
  33.             return false;
  34.         }
  35.         // only vote on Product objects inside this voter
  36.         if (! $subject instanceof Product) {
  37.             return false;
  38.         }
  39.         return true;
  40.     }
  41.     /**
  42.      * @param string $attribute
  43.      * @param Product $entity
  44.      *
  45.      * @return bool
  46.      * @throws Exception
  47.      */
  48.     protected function voteOnAttribute($attribute$entityTokenInterface $token): bool
  49.     {
  50.         $userEntity $token->getUser();
  51.         if (! $userEntity instanceof UserEntity) {
  52.             // the user must be logged in; if not, deny access
  53.             return false;
  54.         }
  55.         $this->user->setEntity($userEntity);
  56.         switch ($attribute) {
  57.             case self::MANAGE_MERCU:
  58.                 return $this->user->canManageCurrentShopMercu();
  59.             case self::CREATE_GUEST_PRODUCT:
  60.                 return $this->user->canManageCurrentShopGuestProducts();
  61.             case self::MANAGE_GUEST_PRODUCT:
  62.                 $product $this->productFactory->createModel($entity);
  63.                 return $product->canBeManagedBy($this->user);
  64.             case self::READ_GUEST_PRODUCT:
  65.                 $product $this->productFactory->createModel($entity);
  66.                 return $product->canBeSeenBy($this->user);
  67.         }
  68.         return false;
  69.     }
  70. }