src/Security/Voter/DeletePropertyCertificateVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\AbstractCollaborator;
  4. use App\Entity\CertificateOfOwnershipFile;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. use Exception;
  10. class DeletePropertyCertificateVoter extends Voter
  11. {
  12.     public const CERTIFICATE_DELETE 'CERTIFICATE_DELETE';
  13.     /**
  14.      * @var Security
  15.      */
  16.     private Security $security;
  17.     /**
  18.      * @param Security $security
  19.      */
  20.     public function __construct(Security $security)
  21.     {
  22.         $this->security $security;
  23.     }
  24.     /**
  25.      * @param string $attribute
  26.      * @param mixed $subject
  27.      * @return bool
  28.      */
  29.     protected function supports(string $attribute$subject): bool
  30.     {
  31.         return $attribute === self::CERTIFICATE_DELETE && $subject instanceof CertificateOfOwnershipFile;
  32.     }
  33.     /**
  34.      * @param string $attribute
  35.      * @param $subject
  36.      * @param TokenInterface $token
  37.      * @return bool
  38.      * @throws Exception
  39.      */
  40.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token)
  41.     {
  42.         /** @var UserInterface $user */
  43.         $user $token->getUser();
  44.         // Deny anonymous users
  45.         if (!$user instanceof UserInterface) {
  46.             return false;
  47.         }
  48.         /** @var CertificateOfOwnershipFile $subject */
  49.         if ($attribute == self::CERTIFICATE_DELETE) {
  50.             if ($subject->getProperty()->getCollaborator()->getUserIdentifier() === $user->getUserIdentifier() || $this->security->isGranted(AbstractCollaborator::ROLE_MANAGER)) {
  51.                 return true;
  52.             }
  53.             return false;
  54.         }
  55.         throw new Exception(sprintf('Unhandled attribute "%s"'$attribute));
  56.     }
  57. }