<?php
namespace App\Security\Core\Authorization;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
/**
*
*/
final class AuthorizationTester
{
private TokenStorageInterface $tokenStorage;
private AuthenticationManagerInterface $authenticationManager;
private AccessTesterManager $accessTesterManager;
private bool $alwaysAuthenticate;
/**
* @param TokenStorageInterface $tokenStorage
* @param AuthenticationManagerInterface $authenticationManager
* @param AccessTesterManager $accessTesterManager
* @param bool $alwaysAuthenticate
*/
public function __construct(
TokenStorageInterface $tokenStorage,
AuthenticationManagerInterface $authenticationManager,
AccessTesterManager $accessTesterManager,
bool $alwaysAuthenticate = false
)
{
$this->tokenStorage = $tokenStorage;
$this->authenticationManager = $authenticationManager;
$this->accessTesterManager = $accessTesterManager;
$this->alwaysAuthenticate = $alwaysAuthenticate;
}
/**
* @param string|array<string> $attributes
* @return bool
*/
public function maybeGranted($attributes): bool
{
if (null === ($token = $this->tokenStorage->getToken())) {
throw new AuthenticationCredentialsNotFoundException('The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.');
}
if ($this->alwaysAuthenticate || !$token->isAuthenticated()) {
$this->tokenStorage->setToken($token = $this->authenticationManager->authenticate($token));
}
if (!\is_array($attributes)) {
$attributes = [$attributes];
}
return $this->accessTesterManager->decide($token, $attributes);
}
/**
* @param string|array<string> $attributes
* @return array<string>
*/
public function whichGranted($attributes): array
{
if ( ! is_array($attributes)) {
$attributes = [$attributes];
}
$results = [];
foreach ($attributes as $attribute) {
if ($attribute && $this->maybeGranted($attribute)) {
$results[] = $attribute;
}
}
return $results;
}
}