src/Security/Voter/ForumPostVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\ForumPost;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. class ForumPostVoter extends Voter
  8. {
  9.     public const EDIT 'EDIT';
  10.     public const DELETE 'DELETE';
  11.     protected function supports(string $attribute$subject): bool
  12.     {
  13.         // replace with your own logic
  14.         // https://symfony.com/doc/current/security/voters.html
  15.         return in_array($attribute, [self::EDITself::DELETE])
  16.             && $subject instanceof ForumPost;
  17.     }
  18.     protected function voteOnAttribute(string $attribute$forumPostTokenInterface $token): bool
  19.     {
  20.         $user $token->getUser();
  21.         // if the user is anonymous, do not grant access
  22.         if (!$user instanceof UserInterface) {
  23.             return false;
  24.         }
  25.         if (null == $forumPost->getUser()) {
  26.             return false;
  27.         }
  28.         // ... (check conditions and return true to grant permission) ...
  29.         switch ($attribute) {
  30.             case self::EDIT:
  31.                 if ($user == $forumPost->getUser()) {
  32.                     return true;
  33.                 }
  34.                 break;
  35.             case self::DELETE:
  36.                 if ($user == $forumPost->getUser()) {
  37.                     return true;
  38.                 }
  39.                 break;
  40.         }
  41.         return false;
  42.     }
  43. }