src/Security/Voter/JvnMediaVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\JvnDevice;
  4. use App\Entity\JvnMedia;
  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. use Symfony\Component\Security\Core\User\UserInterface;
  9. class JvnMediaVoter extends Voter
  10. {
  11.     private Security $security;
  12.     public function __construct(Security $security)
  13.     {
  14.         $this->setSecurity($security);
  15.     }
  16.     /**
  17.      * @return Security
  18.      */
  19.     public function getSecurity(): Security {
  20.         return $this->security;
  21.     }
  22.     /**
  23.      * @param Security $security
  24.      * @return JvnMediaVoter
  25.      */
  26.     public function setSecurity(Security $security): JvnMediaVoter {
  27.         $this->security $security;
  28.         return $this;
  29.     }
  30.     protected function supports($attribute$subject)
  31.     {
  32.         // replace with your own logic
  33.         // https://symfony.com/doc/current/security/voters.html
  34.         return in_array($attribute, ['MEDIA_DELETE'])
  35.             && $subject instanceof JvnMedia;
  36.     }
  37.     /**
  38.      * @param string $attribute
  39.      * @param JvnMedia $subject
  40.      * @param TokenInterface $token
  41.      * @return bool
  42.      */
  43.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  44.     {
  45.         /** @var JvnDevice $user */
  46.         $user $token->getUser();
  47.         // if the user is anonymous, do not grant access
  48.         if (!$user instanceof UserInterface) {
  49.             return false;
  50.         }
  51.         // ... (check conditions and return true to grant permission) ...
  52.         switch ($attribute) {
  53.             case 'MEDIA_DELETE':
  54.                 return
  55.                     $user->getOperario()->getId()->toString() === $subject->getOwner()->getId()->toString() ||
  56.                     $this->getSecurity()->isGranted('ROLE_SUPERVISOR');
  57.         }
  58.         return false;
  59.     }
  60. }