src/Security/Voters/TicketVoter.php line 15

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voters;
  3. use App\Entity\Ticket;
  4. use App\Entity\User;
  5. use App\Entity\Manufacturer;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class TicketVoter extends Voter
  10. {
  11.     private Security $security;
  12.     public const CAN_ADD_UPLOAD     'ticket.can.add.upload';
  13.     public const CAN_EDIT           'ticket.can.be.edited';
  14.     public const CAN_RESOLVE        'ticket.can_resolve';
  15.     private const ATTRIBUTES = [
  16.         self::CAN_ADD_UPLOAD,
  17.         self::CAN_EDIT,
  18.         self::CAN_RESOLVE,
  19.     ];
  20.     public function __construct(Security $security)
  21.     {
  22.         $this->security $security;
  23.     }
  24.     protected function supports($attribute$subject): bool
  25.     {
  26.         return in_array($attributeself::ATTRIBUTES);
  27.     }
  28.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  29.     {
  30.         $user $token->getUser();
  31.         switch ($attribute) {
  32.             case self::CAN_ADD_UPLOAD:
  33.                 return $this->canAddUpload($subject);
  34.             case self::CAN_EDIT:
  35.                 return $this->canEdit($subject);
  36.             case self::CAN_RESOLVE:
  37.                 return $this->canResolve($subject);
  38.         }
  39.         throw new \LogicException('Invalid attribute: ' $attribute);
  40.     }
  41.     private function canEdit(Ticket $ticket): bool
  42.     {
  43.         if ($this->security->isGranted('ROLE_IT_SUPPORT')) {
  44.             return true;
  45.         }
  46.         if ( in_array($ticket->getStatus(), [Ticket::STATUS_NEW]) && $ticket->getCreatedBy() === $this->security->getUser()) {
  47.             return true;
  48.         }
  49.         return false;
  50.     }
  51.     private function canAddUpload(Ticket $ticket): bool
  52.     {
  53.         if ($this->security->isGranted('ROLE_IT_SUPPORT')) {
  54.             return true;
  55.         }
  56.         
  57.         if ( in_array($ticket->getStatus(), [Ticket::STATUS_NEW]) && $ticket->getCreatedBy() === $this->security->getUser()) {
  58.             return true;
  59.         }
  60.         return false;
  61.     }
  62.   
  63.     private function canResolve($subject) : bool
  64.     {
  65.         if ( $this->security->isGranted('ROLE_IT_SUPPORT') ) {
  66.             return true;
  67.         }
  68.         return false;
  69.     }
  70. }