src/FMT/Application/Voter/CartVoter.php line 15

Open in your IDE?
  1. <?php
  2. namespace FMT\Application\Voter;
  3. use FMT\Data\Entity\CampaignProductInterface;
  4. use FMT\Data\Entity\User;
  5. use FMT\Domain\Service\CartManagerInterface;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. /**
  9.  * Class CartVoter
  10.  * @package FMT\Application\Voter
  11.  */
  12. class CartVoter extends Voter
  13. {
  14.     const CAN_ADD_TO_CART 'canAddToCart';
  15.     const CAN_REMOVE_FROM_CART 'canRemoveFromCart';
  16.     /**
  17.      * @var CartManagerInterface
  18.      */
  19.     private $cartManager;
  20.     /**
  21.      * CartVoter constructor.
  22.      * @param CartManagerInterface $cartManager
  23.      */
  24.     public function __construct(CartManagerInterface $cartManager)
  25.     {
  26.         $this->cartManager $cartManager;
  27.     }
  28.     /**
  29.      * @param string $attribute
  30.      * @param mixed $subject
  31.      * @return bool
  32.      * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  33.      */
  34.     protected function supports($attribute$subject)
  35.     {
  36.         if (!in_array($attribute, [
  37.             self::CAN_ADD_TO_CART,
  38.             self::CAN_REMOVE_FROM_CART,
  39.         ])) {
  40.             return false;
  41.         }
  42.         return true;
  43.     }
  44.     /**
  45.      * @param string $attribute
  46.      * @param mixed $subject
  47.      * @param TokenInterface $token
  48.      * @return bool
  49.      * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  50.      */
  51.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  52.     {
  53.         /** @var User $user */
  54.         $user $token->getUser();
  55.         if (method_exists($this$attribute)) {
  56.             return $this->$attribute($user$subject);
  57.         }
  58.         return false;
  59.     }
  60.     /**
  61.      * @param User|string $user
  62.      * @param CampaignProductInterface $product
  63.      * @return bool
  64.      * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  65.      */
  66.     protected function canAddToCart($userCampaignProductInterface $product)
  67.     {
  68.         $isSchoolActive $product->getCampaign()->getSchool()->isActive();
  69.         return $isSchoolActive && $this->cartManager->canAddProduct($product);
  70.     }
  71.     /**
  72.      * @param User|string $user
  73.      * @param CampaignProductInterface $product
  74.      * @return bool
  75.      * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  76.      */
  77.     protected function canRemoveFromCart($userCampaignProductInterface $product)
  78.     {
  79.         return $this->cartManager->hasProduct($product);
  80.     }
  81. }