src/Security/Voter/ProductVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Product;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. class ProductVoter extends Voter
  9. {
  10.     const VIEW 'view';
  11.     const EDIT 'edit';
  12.     const DELETE 'delete';
  13.     const EVALUATE 'evaluate';
  14.     private $security;
  15.     public function __construct(Security $security)
  16.     {
  17.         $this->security $security;
  18.     }
  19.     protected function supports($attribute$subject)
  20.     {
  21.         if (!in_array($attribute, [self::VIEWself::EDITself::DELETEself::EVALUATE])) {
  22.             return false;
  23.         }
  24.         if (!$subject instanceof Product) {
  25.             return false;
  26.         }
  27.         return true;
  28.     }
  29.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  30.     {
  31.         $user $token->getUser();
  32.         if ( !$user instanceof User && $attribute !== self::VIEW ) {
  33.             return false;
  34.         }
  35.         /** @var Product $product */
  36.         $product $subject;
  37.         if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) {
  38.             return true;
  39.         }
  40.         switch ($attribute) {
  41.             case self::VIEW:
  42.                 return $this->canView($product);
  43.             case self::EDIT:
  44.                 return $this->canEdit();
  45.             case self::DELETE:
  46.                 return $this->canDelete();
  47.             case self::EVALUATE:
  48.                 return $this->canEvaluate($product);
  49.         }
  50.         throw new \LogicException('This code should not be reached!');
  51.     }
  52.     private function canView(Product $product)
  53.     {
  54.         return (
  55.             ($this->security->isGranted(User::ROLE_PRODUCT_ADMIN)) ||
  56.             ($product->getStatus() == Product::STATUS_SHOW)
  57.         );
  58.     }
  59.     private function canEdit()
  60.     {
  61.         return $this->security->isGranted(User::ROLE_PRODUCT_ADMIN);
  62.     }
  63.     private function canDelete()
  64.     {
  65.         return $this->security->isGranted(User::ROLE_PRODUCT_ADMIN);
  66.     }
  67.     private function canEvaluate(Product $product)
  68.     {
  69.         return $product->getStatus() == Product::STATUS_SHOW;
  70.     }
  71. }