src/Security/UserVoter.php line 9

  1. <?php
  2. namespace App\Security;
  3. use App\Entity\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. class UserVoter extends Voter
  7. {
  8.     public const DELETE 'delete';
  9.     public const EDIT 'edit';
  10.     public const SHOW 'show';
  11.     public const CREATE 'create';
  12.     /**
  13.      * {@inheritdoc}
  14.      */
  15.     protected function supports(string $attribute$subject): bool
  16.     {
  17.         //dd($attribute, $subject);
  18.         // this voter is only executed on User objects and for four specific permissions
  19.         return $subject instanceof User && \in_array($attribute, [self::SHOWself::CREATEself::EDITself::DELETE], true);
  20.     }
  21.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  22.     {
  23.         $user $token->getUser();
  24.         // the user must be logged in; if not, deny permission
  25.         if (!$user instanceof User) {
  26.             return false;
  27.         }
  28.         if (\in_array(User::ROLE_ADMIN$user->getRoles(), true)) {
  29.             return true;
  30.         } else  {
  31.             if (\in_array(User::ROLE_INSTRUCTOR$user->getRoles(), true)) {
  32.                 return true;
  33.             }
  34.         }
  35.         return ($user->getRoles() === $subject->getAuthor());
  36.     }
  37. }