src/Core/Security/Voters/ApiVoter.php line 11

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Core\Security\Voters;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class ApiVoter extends Voter
  8. {
  9.     /**
  10.      * Determines if the attribute and subject are supported by this voter.
  11.      *
  12.      * @param string $attribute An attribute
  13.      * @param mixed  $subject   The subject to secure, e.g. an object the user wants to access or any other PHP type
  14.      *
  15.      * @return bool True if the attribute and subject are supported, false otherwise
  16.      */
  17.     protected function supports($attribute$subject)
  18.     {
  19.         if (!\in_array($attribute, [User::ROLE_API_READUser::ROLE_API_WRITE], true)) {
  20.             return false;
  21.         }
  22.         return true;
  23.     }
  24.     /**
  25.      * Perform a single access check operation on a given attribute, subject and token.
  26.      * It is safe to assume that $attribute and $subject already passed the "supports()" method check.
  27.      *
  28.      * @param string         $attribute
  29.      * @param mixed          $subject
  30.      * @param TokenInterface $token
  31.      *
  32.      * @return bool
  33.      */
  34.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  35.     {
  36.         $user $token->getUser();
  37.         if (!$user instanceof User) {
  38.             return false;
  39.         }
  40.         switch ($attribute) {
  41.             case User::ROLE_API_READ:
  42.                 return $this->canRead($user);
  43.             case User::ROLE_API_WRITE:
  44.                 return $this->canWrite($user);
  45.         }
  46.         throw new \LogicException('This code should not be reached!');
  47.     }
  48.     private function canRead(User $user): bool
  49.     {
  50.         return \in_array(User::ROLE_API_WRITE$user->getRoles(), true) ||
  51.             \in_array(User::ROLE_API_READ$user->getRoles(), true);
  52.     }
  53.     private function canWrite(User $user): bool
  54.     {
  55.         return \in_array(User::ROLE_API_WRITE$user->getRoles(), true);
  56.     }
  57. }