src/Security/Voter/CreatedByVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Symfony\Component\Security\Core\Security;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. class CreatedByVoter extends Voter
  8. {
  9.     /**
  10.      * @var Security
  11.      */
  12.     private Security $security;
  13.     public function __construct(Security $security)
  14.     {
  15.         $this->security $security;
  16.     }
  17.     protected function supports($attribute$subject)
  18.     {
  19.         // Make sure the voter is used only if the role creator is used and if the subject has a "getCreatedBy" function
  20.         return in_array($attribute, ['ROLE_CREATOR'])
  21.             && method_exists($subject'getCreatedBy')
  22.         ;
  23.     }
  24.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  25.     {
  26.         $user $token->getUser();
  27.         // if the user is anonymous, do not grant access
  28.         if (!$user instanceof UserInterface) {
  29.             return false;
  30.         }
  31.         // Allow admins
  32.         /*if ($this->security->isGranted('ROLE_ADMIN')) {
  33.             return true;
  34.         }*/
  35.         // Allow if user match
  36.         return $subject->getCreatedBy() === $user;
  37.     }
  38. }