src/Security/Voter/FreematicaReportVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\FreematicaReport;
  4. use App\Entity\ContractLine;
  5. use App\Entity\User;
  6. use LogicException;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\Security;
  10. class FreematicaReportVoter extends Voter
  11. {
  12.     public const EDIT 'edit_freematica_report';
  13.     public const SHOW 'show_freematica_report';
  14.     /** @var Security $security */
  15.     private $security;
  16.     /**
  17.      * FreematicaReportVoter constructor.
  18.      * @param Security $security
  19.      */
  20.     public function __construct(Security $security)
  21.     {
  22.         $this->security $security;
  23.     }
  24.     /**
  25.      * @inheritDoc
  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, [self::EDITself::SHOW])) {
  31.             return false;
  32.         }
  33.         // only vote on ContractLine objects inside this voter
  34.         if (!$subject instanceof ContractLine && !$subject instanceof FreematicaReport) {
  35.             return false;
  36.         }
  37.         return true;
  38.     }
  39.     /**
  40.      * @inheritDoc
  41.      */
  42.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  43.     {
  44.         $user $token->getUser();
  45.         if (!$user instanceof User) {
  46.             // the user must be logged in; if not, deny access
  47.             return false;
  48.         }
  49.         switch ($attribute) {
  50.             case self::EDIT:
  51.                 return $this->canEdit($subject);
  52.             case self::SHOW:
  53.                 return $this->canShow();
  54.         }
  55.         throw new LogicException('This code should not be reached!');
  56.     }
  57.     /**
  58.      * @param FreematicaReport $report
  59.      * @return bool
  60.      */
  61.     private function canEdit(FreematicaReport $report): bool
  62.     {
  63.         $collectiveLine $report->getContractLine();
  64.         return ($this->security->isGranted('ROLE_ATCLIENTE') && $collectiveLine->getEnabledRelevantPeriod());
  65.     }
  66.     /**
  67.      * @return bool
  68.      */
  69.     private function canShow(): bool
  70.     {
  71.         return $this->security->isGranted('ROLE_ATCLIENTE');
  72.     }
  73. }