src/Voter/RegistrationVoter.php line 12

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