<?php
declare(strict_types=1);
namespace Comalia\GesicaBundle\Service;
use Symfony\Component\HttpClient\DecoratorTrait;
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* Class HttpClient
*
* Cette class décore le HttpClient de Symfony pour ajouter automatiquement
* le correlation ID dans le header de toutes les "Request" HTTP sortantes
*
* Pour plus d'informations sur le pattern "Decorator' :
* https://symfony.com/doc/current/service_container/service_decoration.html
*/
class HttpClient implements HttpClientInterface
{
// Implémentation de la méthode withOptions demandé par l'interface HttpClientInterface
use DecoratorTrait;
/**
* @var HttpClientInterface
*/
private $decorated;
/**
* @var RequestStack
*/
private $requestStack;
/**
* @var KernelInterface
*/
private $kernel;
/**
* HttpClient constructor.
* @param HttpClientInterface $decorated
* @param RequestStack $requestStack
* @param KernelInterface $kernel
*/
public function __construct(HttpClientInterface $decorated, RequestStack $requestStack, KernelInterface $kernel)
{
$this->decorated = $decorated;
$this->requestStack = $requestStack;
$this->kernel = $kernel;
}
/**
* @inheritDoc
*/
public function request(string $method, string $url, array $options = []): ResponseInterface
{
$session = $this->getSession();
if ($session) {
$options['headers']['x-correlation-id'] = $session->get('x-correlation-id');
}
return $this->decorated->request($method, $url, $options);
}
/**
* @inheritDoc
*/
public function stream($responses, float $timeout = null): ResponseStreamInterface
{
return $this->decorated->stream($responses, $timeout);
}
/**
* @return SessionInterface
*/
private function getSession(): ?SessionInterface
{
try {
return $this->requestStack->getSession();
} catch (SessionNotFoundException $ex) {
return null;
}
}
}