src/Voter/MessageVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Voter;
  3. use App\Entity\User;
  4. use App\Model\Message;
  5. use LogicException;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class MessageVoter extends Voter
  9. {
  10.     public const DISCARD 'discard';
  11.     public const ACTION 'action';
  12.     /**
  13.      * Determines if the attribute and subject are supported by this voter.
  14.      *
  15.      * @param string $attribute An attribute
  16.      * @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
  17.      *
  18.      * @return bool True if the attribute and subject are supported, false otherwise
  19.      */
  20.     protected function supports($attribute$subject): bool
  21.     {
  22.         // if the attribute isn't one we support, return false
  23.         if (!in_array($attribute, [self::DISCARDself::ACTION])) {
  24.             return false;
  25.         }
  26.         // only vote on Message objects inside this voter
  27.         if (!$subject instanceof \App\Entity\Message) {
  28.             return false;
  29.         }
  30.         return true;
  31.     }
  32.     /**
  33.      * Perform a single access check operation on a given attribute, subject and token.
  34.      * It is safe to assume that $attribute and $subject already passed the "supports()" method check.
  35.      *
  36.      * @param string $attribute
  37.      * @param mixed $subject
  38.      *
  39.      * @return bool
  40.      */
  41.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  42.     {
  43.         /**
  44.          * User
  45.          */
  46.         $user $token->getUser();
  47.         if (!$user instanceof User) {
  48.             // the user must be logged in; if not, deny access
  49.             return false;
  50.         }
  51.         $message = new Message();
  52.         $message->setEntity($subject);
  53.         switch ($attribute) {
  54.             case self::DISCARD:
  55.                 return $message->canBeDiscardedBy($user);
  56.             case self::ACTION:
  57.                 return $message->canBeActionedBy($user);
  58.         }
  59.         throw new LogicException('This code should not be reached!');
  60.     }
  61. }