<?php
namespace App\Security;
use App\Service\Access;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
class UrlVoters extends Voter implements VoterInterface
{
private RouterInterface $routerService;
private ?array $route = null;
private ?string $url = null;
private RequestStack $requestStack;
private Access $access;
public function __construct(RouterInterface $router, Access $access, RequestStack $requestStack)
{
$this->access = $access;
$this->routerService = $router;
$this->requestStack = $requestStack;
}
protected function supports(string $attribute, $subject): bool
{
$urlArray = explode('?', (string) $this->requestStack->getMainRequest()->server->get('REQUEST_URI'));
$anonListUrls = $this->access->getAnonListUrls();
$this->url = $urlArray[0];
if (preg_match('![\W]-!', preg_replace('!/!', '', $this->url))) {
return true;
}
$this->route = $this->routerService->match($this->url);
foreach ($anonListUrls as $url) {
if (isset($this->route['_route'])) {
if (preg_match('!' . $url . '!', (string) $this->route['_route'])) {
return false;
}
}
}
return true;
}
/**
* @param string $attribute
* @param object|string|null $subject
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool|string
{
if (preg_match('![\W]-!', preg_replace('!/!', '', $this->url))) {
return false;
}
return $this->access->checkUrl($this->url);
}
}