src/Security/Voter/GalleryVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\Security;
  7. class GalleryVoter extends Voter
  8. {
  9.     const EDIT 'edit';
  10.     const MANAGE 'manage';
  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::EDITself::MANAGE])) {
  19.             return false;
  20.         }
  21.         if (!$subject instanceof User) {
  22.             return false;
  23.         }
  24.         return true;
  25.     }
  26.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  27.     {
  28.         $currentUser $token->getUser();
  29.         if (!$currentUser instanceof User) {
  30.             return false;
  31.         }
  32.         /** @var User $user */
  33.         $user $subject;
  34.         if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) {
  35.             return true;
  36.         }
  37.         switch ($attribute) {
  38.             case self::EDIT:
  39.             case self::MANAGE:
  40.                 return $this->canEdit($user$currentUser$token);
  41.         }
  42.         throw new \LogicException('This code should not be reached!');
  43.     }
  44.     private function canEdit(User $userUser $currentUserTokenInterface $token)
  45.     {
  46.         return $user === $currentUser || $this->security->isGranted(User::ROLE_GALLERY_ADMIN);
  47.     }
  48. }