src/App/Security/Core/Authorization/AuthorizationTester.php line 48

Open in your IDE?
  1. <?php
  2. namespace App\Security\Core\Authorization;
  3. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  4. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  5. use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  6. /**
  7.  *
  8.  */
  9. final class AuthorizationTester
  10. {
  11.     private TokenStorageInterface $tokenStorage;
  12.     private AuthenticationManagerInterface $authenticationManager;
  13.     private AccessTesterManager $accessTesterManager;
  14.     private bool $alwaysAuthenticate;
  15.     /**
  16.      * @param TokenStorageInterface $tokenStorage
  17.      * @param AuthenticationManagerInterface $authenticationManager
  18.      * @param AccessTesterManager $accessTesterManager
  19.      * @param bool $alwaysAuthenticate
  20.      */
  21.     public function __construct(
  22.         TokenStorageInterface $tokenStorage,
  23.         AuthenticationManagerInterface $authenticationManager,
  24.         AccessTesterManager $accessTesterManager,
  25.         bool $alwaysAuthenticate false
  26.     )
  27.     {
  28.         $this->tokenStorage $tokenStorage;
  29.         $this->authenticationManager $authenticationManager;
  30.         $this->accessTesterManager $accessTesterManager;
  31.         $this->alwaysAuthenticate $alwaysAuthenticate;
  32.     }
  33.     /**
  34.      * @param string|array<string> $attributes
  35.      * @return bool
  36.      */
  37.     public function maybeGranted($attributes): bool
  38.     {
  39.         if (null === ($token $this->tokenStorage->getToken())) {
  40.             throw new AuthenticationCredentialsNotFoundException('The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.');
  41.         }
  42.         if ($this->alwaysAuthenticate || !$token->isAuthenticated()) {
  43.             $this->tokenStorage->setToken($token $this->authenticationManager->authenticate($token));
  44.         }
  45.         if (!\is_array($attributes)) {
  46.             $attributes = [$attributes];
  47.         }
  48.         return $this->accessTesterManager->decide($token$attributes);
  49.     }
  50.     /**
  51.      * @param string|array<string> $attributes
  52.      * @return array<string>
  53.      */
  54.     public function whichGranted($attributes): array
  55.     {
  56.         if ( ! is_array($attributes)) {
  57.             $attributes = [$attributes];
  58.         }
  59.         $results = [];
  60.         foreach ($attributes as $attribute) {
  61.             if ($attribute && $this->maybeGranted($attribute)) {
  62.                 $results[] = $attribute;
  63.             }
  64.         }
  65.         return $results;
  66.     }
  67. }