<?php declare(strict_types=1);
namespace Shopware\B2B\AclRoute\BridgePlatform;
use Shopware\B2B\AclRoute\Framework\AclRouteService;
use Shopware\B2B\Common\Controller\B2bControllerRedirectException;
use Shopware\Core\Framework\Routing\KernelListenerPriorities;
use SwagB2bPlatform\Routing\RouteLoader;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestInterceptorSubscriber implements EventSubscriberInterface
{
const ERROR_ACTION = 'error';
const ERROR_CONTROLLER = 'b2bacl';
/**
* @var AclRouteService
*/
private $aclRoutingService;
public function __construct(
AclRouteService $aclRoutingService
) {
$this->aclRoutingService = $aclRoutingService;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => ['redirectIfInaccessible', KernelListenerPriorities::KERNEL_CONTROLLER_EVENT_SCOPE_VALIDATE_POST],
];
}
public function redirectIfInaccessible(KernelEvent $event): void
{
$request = $event->getRequest();
$controller = $request->attributes->get(RouteLoader::ROUTE_CONTROLLER_ROUTE_NAME) ?? '';
$action = $request->attributes->get(RouteLoader::ROUTE_CONTROLLER_ACTION) ?? '';
if ($action === self::ERROR_ACTION && $controller === self::ERROR_CONTROLLER) {
return;
}
$allowed = $this->aclRoutingService
->isRouteAllowed($controller, $action);
if (!$allowed) {
$event->setController(function (): void {
throw new B2bControllerRedirectException(self::ERROR_ACTION, self::ERROR_CONTROLLER);
});
}
}
}