src/Security/BatchVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use App\Entity\User;
  7. use App\Entity\Batch;
  8. /**
  9.  *
  10.  * @author "wendell.zheng <wxzheng@ustc.edu.cn>"
  11.  */
  12. class BatchVoter extends Voter
  13. {
  14.     const APPLICANT_ACTION 'applicant_action';
  15.     const COLLEGE_ACTION 'college_action';
  16.     protected $em;
  17.     public function __construct(EntityManagerInterface $em)
  18.     {
  19.         $this->em $em;
  20.     }
  21.     protected function supports($attribute$subject): bool
  22.     {
  23.         if (! in_array($attribute, [
  24.             self::APPLICANT_ACTION,
  25.             self::COLLEGE_ACTION
  26.         ])) {
  27.             return false;
  28.         }
  29.         if (! $subject instanceof Batch) {
  30.             return false;
  31.         }
  32.         return true;
  33.     }
  34.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  35.     {
  36.         $user $token->getUser();
  37.         if (! $user instanceof User) {
  38.             return false;
  39.         }
  40.         if ($user->getUserIdentifier() == 'P0336') {
  41.             return true;
  42.         }
  43.         /** @var Batch $batch */
  44.         $batch $subject;
  45.         switch ($attribute) {
  46.             case self::APPLICANT_ACTION:
  47.                 return $this->canApplicantAction($batch$user);
  48.             case self::COLLEGE_ACTION:
  49.                 return $this->canCollegeAction($batch$user);
  50.         }
  51.         throw new \LogicException('This code should not be reached!');
  52.     }
  53.     protected function canApplicantAction(Batch $batchUser $user): bool
  54.     {
  55.         return $batch->isApplyActive();
  56.     }
  57.     protected function canCollegeAction(Batch $batchUser $user): bool
  58.     {
  59.         return $batch->isCollegeActive();
  60.     }
  61. }