<?php
declare(strict_types=1);
namespace Comalia\GesicaBundle\EventSubscriber;
use Comalia\GesicaBundle\Service\CorrelationIdService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class CorrelationIdAuditSubscriber implements EventSubscriberInterface
{
/**
* kernel.request priority
* 40 : pour déclencher le subscriber avant le correlationIdProcessor
*/
const REQUEST_POST_READ = 40;
/**
* @var CorrelationIdService
*/
private $correlationIdService;
/** @var RequestStack */
private $requestStack;
/**
* CorrelationIdAuditSubscriber constructor.
* @param CorrelationIdService $correlationIdService
* @param RequestStack $requestStack
*/
public function __construct(CorrelationIdService $correlationIdService, RequestStack $requestStack)
{
$this->correlationIdService = $correlationIdService;
$this->requestStack = $requestStack;
}
/**
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
$session = $this->getSession();
if ($session) {
if ($request->headers->has('x-correlation-id') === false) {
$session->set('x-correlation-id', $this->correlationIdService->getCorrelationId());
return;
}
$session->set('x-correlation-id', $request->headers->get('x-correlation-id'));
$request->setSession($session);
}
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', self::REQUEST_POST_READ]
];
}
/**
* @return SessionInterface
*/
private function getSession(): ?SessionInterface
{
try {
return $this->requestStack->getSession();
} catch (SessionNotFoundException $ex) {
return null;
}
}
}