src/Security/Voter/User/AmateurUpgradeVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter\User;
  3. use App\Entity\Account;
  4. use App\Security\ApiUser;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class AmateurUpgradeVoter extends Voter
  8. {
  9.     public const PERMISSION_UPGRADE 'upgrade';
  10.     protected function supports(string $attribute$subject): bool
  11.     {
  12.         if (!$subject instanceof Account) {
  13.             return false;
  14.         }
  15.         return in_array($attribute, [self::PERMISSION_UPGRADE], true);
  16.     }
  17.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  18.     {
  19.         $user $token->getUser();
  20.         if (!$user instanceof ApiUser) {
  21.             return false;
  22.         }
  23.         /*
  24.          * @var $subject Account
  25.          */
  26.         if (self::PERMISSION_UPGRADE == $attribute) {
  27.             return $this->canUpgrade($subject$user);
  28.         }
  29.         return false;
  30.     }
  31.     protected function canUpgrade(Account $subjectApiUser $user): bool
  32.     {
  33.         // admin should be able to upgrade anyone
  34.         if ($user->getIsAdmin()) {
  35.             return true;
  36.         }
  37.         // active user is already an amateur, so no longer possible
  38.         if ($user->getIsAmateur()) {
  39.             return false;
  40.         }
  41.         return $user->getAccount()->getId() === $subject->getId();
  42.     }
  43. }