Forward request ID from sync request process to async job processes

This commit is contained in:
Alejandro Celaya
2024-04-07 11:26:17 +02:00
parent cc134abd12
commit e1cf0c4ea7
6 changed files with 84 additions and 3 deletions

View File

@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Shlinkio\Shlink\Core\EventDispatcher\Helper;
use Shlinkio\Shlink\Common\Middleware\RequestIdMiddleware;
use Shlinkio\Shlink\EventDispatcher\Util\RequestIdProviderInterface;
readonly class RequestIdProvider implements RequestIdProviderInterface
{
public function __construct(private RequestIdMiddleware $requestIdMiddleware)
{
}
public function currentRequestId(): string
{
return $this->requestIdMiddleware->currentRequestId();
}
}

View File

@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace ShlinkioTest\Shlink\Core\EventDispatcher\Helper;
use Laminas\Diactoros\Response;
use Laminas\Diactoros\ServerRequestFactory;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Psr\Http\Server\RequestHandlerInterface;
use Shlinkio\Shlink\Common\Middleware\RequestIdMiddleware;
use Shlinkio\Shlink\Core\EventDispatcher\Helper\RequestIdProvider;
class RequestIdProviderTest extends TestCase
{
private RequestIdProvider $provider;
private RequestIdMiddleware $middleware;
protected function setUp(): void
{
$this->middleware = new RequestIdMiddleware();
$this->provider = new RequestIdProvider($this->middleware);
}
#[Test]
public function requestIdTrackedByMiddlewareIsForwarded(): void
{
$initialId = $this->middleware->currentRequestId();
self::assertEquals($initialId, $this->provider->currentRequestId());
$handler = $this->createMock(RequestHandlerInterface::class);
$handler->method('handle')->willReturn(new Response());
$this->middleware->process(ServerRequestFactory::fromGlobals(), $handler);
$idAfterProcessingRequest = $this->middleware->currentRequestId();
self::assertNotEquals($idAfterProcessingRequest, $initialId);
self::assertEquals($idAfterProcessingRequest, $this->provider->currentRequestId());
$manuallySetId = 'foobar';
$this->middleware->setCurrentRequestId($manuallySetId);
self::assertNotEquals($manuallySetId, $idAfterProcessingRequest);
self::assertEquals($manuallySetId, $this->provider->currentRequestId());
}
}