src/Security/Voter/ProductEvaluationVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\ProductVote;
  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 ProductEvaluationVoter extends Voter
  9. {
  10.     const DELETE 'delete';
  11.     private $security;
  12.     public function __construct(Security $security)
  13.     {
  14.         $this->security $security;
  15.     }
  16.     protected function supports($attribute$subject)
  17.     {
  18.         if (!in_array($attribute, [self::DELETE])) {
  19.             return false;
  20.         }
  21.         if (!$subject instanceof ProductVote) {
  22.             return false;
  23.         }
  24.         return true;
  25.     }
  26.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  27.     {
  28.         $user $token->getUser();
  29.         if (!$user instanceof User) {
  30.             return false;
  31.         }
  32.         /** @var ProductVote $evaluation */
  33.         $evaluation $subject;
  34.         if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) {
  35.             return true;
  36.         }
  37.         switch ($attribute) {
  38.             case self::DELETE:
  39.                 return $this->canDelete($evaluation$user$token);
  40.         }
  41.         throw new \LogicException('This code should not be reached!');
  42.     }
  43.     private function canDelete(ProductVote $evaluationUser $userTokenInterface $token)
  44.     {
  45.         return $evaluation->getCreatedBy() === $user;
  46.     }
  47. }