Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ The **SchemaContextBundle** provides a lightweight way to manage dynamic schema

## Features

- Extracts tenant schema from request headers.
- Extracts tenant schema param from baggage request header.
- Stores schema context in a global `SchemaResolver`.
- Injects schema info into Messenger messages via a middleware.
- Rehydrates schema on message consumption via a middleware.
- Provide decorator for Http clients to propagate schema header

---

Expand Down Expand Up @@ -57,6 +58,19 @@ public function index(SchemaResolver $schemaResolver)
}
```

## Schema-Aware HTTP Client
Decorate your http client in your service configuration:
```yaml
services:
schema_aware_payment_http_client:
class: Macpaw\SchemaContextBundle\HttpClient\SchemaAwareHttpClient
decorates: payment_http_client #http client to decorate
arguments:
- '@schema_aware_payment_http_client.inner'
- '@Macpaw\SchemaContextBundle\Service\SchemaResolver'
- '%schema_context.header_name%'
```

## Messenger Integration
The bundle provides a middleware that automatically:

Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"symfony/messenger": "^6.4 || ^7.0",
"symfony/http-kernel": "^6.4 || ^7.0",
"symfony/dependency-injection": "^6.4 || ^7.0",
"symfony/config": "^6.4 || ^7.0"
"symfony/config": "^6.4 || ^7.0",
"symfony/http-client": "^7.3"
},
"require-dev": {
"phpstan/phpstan": "^1.10",
Expand Down
19 changes: 18 additions & 1 deletion src/EventListener/SchemaRequestListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,24 @@ public function onKernelRequest(RequestEvent $event): void
return;
}

$schema = $event->getRequest()->headers->get($this->schemaRequestHeader, $this->defaultSchema);
$request = $event->getRequest();
$baggage = $request->headers->get('baggage');

if ($baggage) {
foreach (explode(',', $baggage) as $part) {
[$key, $value] = array_map(
static fn(?string $v): ?string => $v !== null ? trim($v) : null,
explode('=', $part, 2) + [null, null]
);

if ($key === $this->schemaRequestHeader && $value !== null) {
$schema = $value;
break;
}
}
}

$schema ??= $this->defaultSchema;

if ($schema !== null && $schema !== '') {
$this->schemaResolver->setSchema($schema);
Expand Down
58 changes: 58 additions & 0 deletions src/HttpClient/SchemaAwareHttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

namespace Macpaw\SchemaContextBundle\HttpClient;

use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Macpaw\SchemaContextBundle\Service\SchemaResolver;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;

class SchemaAwareHttpClient implements HttpClientInterface
{
public function __construct(
private HttpClientInterface $inner,
private SchemaResolver $schemaResolver,
private string $schemaRequestHeader
) {
}

/**
* @param array<string, mixed> $options
*/
public function request(string $method, string $url, array $options = []): ResponseInterface
{
$schema = $this->schemaResolver->getSchema();
$baggageHeader = $this->schemaRequestHeader . '=' . $schema;
$headers = isset($options['headers']) && is_array($options['headers'])
? $options['headers']
: [];

if (isset($headers['baggage'])) {
$headers['baggage'] .= ',' . $baggageHeader;
} else {
$headers['baggage'] = $baggageHeader;
}

$options['headers'] = $headers;

return $this->inner->request($method, $url, $options);
}

public function stream(iterable|ResponseInterface $responses, ?float $timeout = null): ResponseStreamInterface
{
return $this->inner->stream($responses, $timeout);
}

/**
* @param array<string, mixed> $options
*/
public function withOptions(array $options): static
{
$wrapped = $this->inner->withOptions($options);

/** @phpstan-ignore-next-line */
return new self($wrapped, $this->schemaResolver, $this->schemaRequestHeader);
}
}
2 changes: 1 addition & 1 deletion tests/EventListener/SchemaRequestListenerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public function testSchemaFromHeaderIsSet(): void
['test-app'],
);

$request = new Request([], [], [], [], [], ['HTTP_X_SCHEMA' => 'tenant1']);
$request = new Request([], [], [], [], [], ['HTTP_BAGGAGE' => 'X-Schema=tenant1']);
$kernel = $this->createMock(HttpKernelInterface::class);
$event = new RequestEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST);

Expand Down
55 changes: 55 additions & 0 deletions tests/HttpClient/SchemaAwareHttpClientTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);

namespace Macpaw\SchemaContextBundle\Tests\HttpClient;

use Macpaw\SchemaContextBundle\HttpClient\SchemaAwareHttpClient;
use Macpaw\SchemaContextBundle\Service\SchemaResolver;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\Response\MockResponse;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

class SchemaAwareHttpClientTest extends TestCase
{
public function testItInjectsSchemaIntoBaggageHeader(): void
{
$expectedSchema = 'tenant_42';
$mockResponse = new MockResponse('OK');
$schemaRequestHeader = 'X-Schema';

$mockClient = $this->createMock(HttpClientInterface::class);
$mockClient
->expects($this->once())
->method('request')
->with(
'GET',
'https://api.example.com/test',
$this->callback(function (array $options) use ($expectedSchema, $schemaRequestHeader) {
$headers = $options['headers'] ?? [];
$baggage = $headers['baggage'] ?? null;

if (is_array($baggage)) {
$baggage = implode(',', $baggage);
}

return is_string($baggage) && str_contains($baggage, $schemaRequestHeader . '=' . $expectedSchema);
})
)
->willReturn($mockResponse);

$schemaResolver = $this->createMock(SchemaResolver::class);
$schemaResolver->method('getSchema')->willReturn($expectedSchema);

$client = new SchemaAwareHttpClient(
$mockClient,
$schemaResolver,
$schemaRequestHeader,
);

$response = $client->request('GET', 'https://api.example.com/test');

self::assertInstanceOf(ResponseInterface::class, $response);
}
}
Loading