<?php
declare(strict_types=1);
namespace App\Listener\Cinema;
use App\Event\Cinema\CinemaContextOnDemandEvent;
use App\WsProxy\WsProxy;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class CinemaContextListener
{
private EventDispatcherInterface $eventDispatcher;
private WsProxy $wsProxy;
public const EXCLUDED_ENDPOINTS = [
[
'method' => 'GET',
'path' => '/user/preferences'
],
[
'method' => 'PUT',
'path' => '/user/preferences'
]
];
/**
* CinemaContextListener constructor.
* @param EventDispatcherInterface $eventDispatcher
* @param WsProxy $wsProxy
*/
public function __construct(EventDispatcherInterface $eventDispatcher, WsProxy $wsProxy)
{
$this->eventDispatcher = $eventDispatcher;
$this->wsProxy = $wsProxy;
}
public function onKernelController(\Symfony\Component\HttpKernel\Event\ControllerEvent $event)
{
$request = $event->getRequest();
$this->wsProxy->setContextLanguage($request->getLocale());
$cinemaId = null;
if ($request->attributes->get('cinemaId')) {
$cinemaId = $request->attributes->get('cinemaId');
}
if ($request->get('cinemaId')) {
$cinemaId = $request->get('cinemaId');
}
if ($cinemaId !== null && !$this->isPathExcluded($request)) {
$this->eventDispatcher->dispatch(
new CinemaContextOnDemandEvent((string) $cinemaId)
);
}
}
private function isPathExcluded(Request $request): bool
{
foreach (self::EXCLUDED_ENDPOINTS as $endpoint) {
if ($endpoint['method'] === $request->getMethod() && $endpoint['path'] === $request->getPathInfo()) {
return true;
}
}
return false;
}
}