src/Security/Voter/PublicationVoter.php line 9

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\User\UserInterface;
  6. class PublicationVoter extends Voter
  7. {
  8.     public const EDIT = 'POST_EDIT';
  9.     public const VIEW = 'POST_VIEW';
  10.     protected function supports(string $attribute, $subject): bool
  11.     {
  12.         // replace with your own logic
  13.         // https://symfony.com/doc/current/security/voters.html
  14.         return in_array($attribute, [self::EDIT, self::VIEW])
  15.             && $subject instanceof \App\Entity\Publication;
  16.     }
  17.     protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
  18.     {
  19.         $user = $token->getUser();
  20.         // if the user is anonymous, do not grant access
  21.         if (!$user instanceof UserInterface) {
  22.             return false;
  23.         }
  24.         // ... (check conditions and return true to grant permission) ...
  25.         switch ($attribute) {
  26.             case self::EDIT:
  27.                 // logic to determine if the user can EDIT
  28.                 if ($subject->getAuthor() == $user) {
  29.                     return true;
  30.                 } else {
  31.                     return false;
  32.                 }
  33.                 // return true or false
  34.                 break;
  35.             case self::VIEW:
  36.                 // logic to determine if the user can VIEW
  37.                 // return true or false
  38.                 if ($subject->getAuthor() == $user) {
  39.                     return true;
  40.                 } else {
  41.                     return false;
  42.                 }
  43.                 break;
  44.         }
  45.         return false;
  46.     }
  47. }