src/Voter/InvitationVoter.php line 15

Open in your IDE?
  1. <?php
  2. namespace App\Voter;
  3. use App\Voter\Supplier;
  4. use App\Voter\SupplierFactory;
  5. use App\Entity\Invitation;
  6. use App\Entity\User;
  7. use App\Model\InvitationFactory;
  8. use App\Model\User\UserFactory;
  9. use Exception;
  10. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  11. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  12. class InvitationVoter extends Voter
  13. {
  14.     public const DELETE 'delete';
  15.     private $userFactory;
  16.     /**
  17.      * @var SupplierFactory
  18.      */
  19.     private $invitationFactory;
  20.     public function __construct(
  21.         UserFactory $userFactory,
  22.         InvitationFactory $invitationFactory
  23.     ) {
  24.         $this->invitationFactory $invitationFactory;
  25.         $this->userFactory       $userFactory;
  26.     }
  27.     protected function supports($attribute$subject): bool
  28.     {
  29.         // if the attribute isn't one we support, return false
  30.         if (! in_array($attribute, [
  31.             self::DELETE
  32.         ])) {
  33.             return false;
  34.         }
  35.         if (! $subject instanceof Invitation) {
  36.             return false;
  37.         }
  38.         return true;
  39.     }
  40.     /**
  41.      * @param string $attribute
  42.      * @param Supplier $entity
  43.      *
  44.      * @return bool
  45.      * @throws Exception
  46.      */
  47.     protected function voteOnAttribute($attribute$entityTokenInterface $token): bool
  48.     {
  49.         $userEntity $token->getUser();
  50.         if (! $userEntity instanceof User) {
  51.             // the user must be logged in; if not, deny access
  52.             return false;
  53.         }
  54.         $user       $this->userFactory->createModel($userEntity);
  55.         $invitation $this->invitationFactory->createModel($entity);
  56.         switch ($attribute) {
  57.             case self::DELETE:
  58.                 return $user->canDeleteInvitation($invitation);
  59.         }
  60.         return false;
  61.     }
  62. }