<?php
namespace App\Subscriber\Routing;
use Cms\CoreBundle\Service\ContextManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Routing\RouterInterface;
final class AppContextSubscriber implements EventSubscriberInterface
{
/**
* @var RouterInterface
*/
protected RouterInterface $router;
/**
* @var ParameterBagInterface
*/
protected ParameterBagInterface $parameters;
/**
* @var ContextManager
*/
protected ContextManager $cm;
/**
* @param RouterInterface $router
* @param ParameterBagInterface $parameters
* @param ContextManager $cm
*/
public function __construct(RouterInterface $router, ParameterBagInterface $parameters, ContextManager $cm)
{
$this->router = $router;
$this->parameters = $parameters;
$this->cm = $cm;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
// NOTE: using "9" for priority as that comes after router but before firewall
KernelEvents::REQUEST => ['onKernelRequest', 9],
];
}
/**
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event): void
{
// obtain the context
$context = $this->router->getContext();
// set the environment variable
$context->setParameter(
'cluster',
$this->parameters->get('app.routing.cluster')
);
// set the shard if we have something to set
if ( ! empty($this->cm->getGlobalContext()->getTenant())) {
$context->setParameter(
'shard',
$this->cm->getGlobalContext()->getTenant()->getSlug()
);
}
}
}