src/Security/Voter/FarmVoter.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Symfony\Component\Security\Core\Security;
  6. class FarmVoter extends Voter
  7. {
  8.     public const EDIT 'POST_EDIT';
  9.     public const VIEW 'POST_VIEW';
  10.     public const ADD 'POST_ADD';
  11.     public const DELETE 'POST_DELETE';
  12.     public function __construct( private readonly Security $security ) {}
  13.     protected function supports(string $attribute$subject): bool
  14.     {
  15.         // replace with your own logic
  16.         // https://symfony.com/doc/current/security/voters.html
  17.         return in_array($attribute, [self::EDITself::VIEWself::ADDself::DELETE])
  18.             && $subject instanceof \App\Entity\Farm;
  19.     }
  20.     /* attribute = accion, y subject es el objeto */
  21.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  22.     {
  23.         $isMyOrganization $this->security->getUser()->getOrganization() == $subject->getOrganization();
  24.         if ($this->security->isGranted('ROLE_ADMIN'))
  25.             return true;
  26.         if ($this->security->isGranted('ROLE_MANAGER')) {
  27.             switch ( $attribute ) {
  28.                 case self::ADD:
  29.                     return true;
  30.                 default:
  31.                     if ($isMyOrganization)
  32.                         return true;
  33.                     return false;
  34.             }
  35.         }
  36.         if ($this->security->isGranted('ROLE_USER')) {
  37.             switch ( $attribute ) {
  38.                 case self::VIEW:
  39.                     if ( $isMyOrganization )
  40.                         return true;
  41.                     return false;
  42.                 default:
  43.                     return false;
  44.             }
  45.         }
  46.         /* respuesta segura al ANON */
  47.         return false;
  48.     }
  49. }