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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,9 @@ stixx_openapi_command:
validation:
enabled: true
groups: ['Default']
cache_control: 'no-store' # Any valid Cache-Control directives, or null to disable
openapi:
problem_details: true # Enable RFC 7807 problem details for errors
problem_details: true # Enable RFC 7807 problem details for errors
```

## Documentation
Expand Down
3 changes: 2 additions & 1 deletion config/controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
->arg('$responder', service(ResponderInterface::class))
->arg('$exceptionUnwrapper', service(WrappedExceptionUnwrapper::class))
->arg('$validationEnabled', param('stixx_openapi_command.validation.enabled'))
->arg('$validationGroups', param('stixx_openapi_command.validation.groups'));
->arg('$validationGroups', param('stixx_openapi_command.validation.groups'))
->arg('$cacheControl', param('stixx_openapi_command.cache_control'));

$services
->set(CommandValueResolver::class)
Expand Down
9 changes: 8 additions & 1 deletion src/Controller/CommandController.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public function __construct(
private bool $validationEnabled = true,
/** @var string[] */
private array $validationGroups = ['Default'],
private ?string $cacheControl = 'no-store',
) {
}

Expand All @@ -63,7 +64,13 @@ public function __invoke(Request $request, #[CommandObject] object $command): Re
$handled = $envelope->last(HandledStamp::class);
$result = $handled?->getResult();

return $this->responder->respond($result, $this->statusResolver->resolve($request, $command));
$response = $this->responder->respond($result, $this->statusResolver->resolve($request, $command));

if (!empty($this->cacheControl)) {
$response->headers->set('Cache-Control', $this->cacheControl);
}

return $response;
}

private function validateCommand(object $command): void
Expand Down
3 changes: 3 additions & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ public function getConfigTreeBuilder(): TreeBuilder
->end()
->end()
->end()
->scalarNode('cache_control')
->defaultValue('no-store')
->end()
->arrayNode('openapi')
->addDefaultsIfNotSet()
->children()
Expand Down
3 changes: 3 additions & 0 deletions src/DependencyInjection/StixxOpenApiCommandExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ public function load(array $configs, ContainerBuilder $container): void

$container->setParameter('stixx_openapi_command.validation.enabled', $validationConfig['enabled']);
$container->setParameter('stixx_openapi_command.validation.groups', $validationConfig['groups']);
/** @var ?string $cacheControl */
$cacheControl = $config['cache_control'];
$container->setParameter('stixx_openapi_command.cache_control', $cacheControl);

$container
->registerForAutoconfiguration(ResponderInterface::class)
Expand Down
20 changes: 20 additions & 0 deletions tests/Functional/Resources/config/cache_control_custom.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

/*
* This file is part of the StixxOpenApiCommandBundle package.
*
* (c) Stixx
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $container): void {
$container->extension('stixx_openapi_command', [
'cache_control' => 'no-cache, must-revalidate',
]);
};
20 changes: 20 additions & 0 deletions tests/Functional/Resources/config/cache_control_disabled.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

/*
* This file is part of the StixxOpenApiCommandBundle package.
*
* (c) Stixx
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $container): void {
$container->extension('stixx_openapi_command', [
'cache_control' => null,
]);
};
63 changes: 63 additions & 0 deletions tests/Functional/ScenarioTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,69 @@ public function testUpdateBookValidationError(): void
self::assertArrayHasKey('violations', $data);
}

#[WithoutErrorHandler]
public function testResponseIncludesDefaultCacheControlHeader(): void
{
// Arrange
$kernel = $this->createKernelWithConfig(static function (Kernel $kernel): void {
$kernel->addTestConfig(__DIR__.'/Resources/config/scenario.php');
});

$payload = ['title' => 'Clean Code', 'author' => 'Robert C. Martin'];
$request = Request::create('/api/books', 'POST', content: json_encode($payload, JSON_THROW_ON_ERROR));
$request->headers->set('Content-Type', 'application/json');

// Act
$response = $kernel->handle($request);

// Assert
self::assertSame(201, $response->getStatusCode());
self::assertStringContainsString('no-store', (string) $response->headers->get('Cache-Control'));
}

#[WithoutErrorHandler]
public function testResponseOmitsCacheControlWhenDisabled(): void
{
// Arrange
$kernel = $this->createKernelWithConfig(static function (Kernel $kernel): void {
$kernel->addTestConfig(__DIR__.'/Resources/config/scenario.php');
$kernel->addTestConfig(__DIR__.'/Resources/config/cache_control_disabled.php');
});

$payload = ['title' => 'Clean Code', 'author' => 'Robert C. Martin'];
$request = Request::create('/api/books', 'POST', content: json_encode($payload, JSON_THROW_ON_ERROR));
$request->headers->set('Content-Type', 'application/json');

// Act
$response = $kernel->handle($request);

// Assert
self::assertSame(201, $response->getStatusCode());
self::assertStringNotContainsString('no-store', (string) $response->headers->get('Cache-Control'));
}

#[WithoutErrorHandler]
public function testResponseIncludesCustomCacheControlHeader(): void
{
// Arrange
$kernel = $this->createKernelWithConfig(static function (Kernel $kernel): void {
$kernel->addTestConfig(__DIR__.'/Resources/config/scenario.php');
$kernel->addTestConfig(__DIR__.'/Resources/config/cache_control_custom.php');
});

$payload = ['title' => 'Clean Code', 'author' => 'Robert C. Martin'];
$request = Request::create('/api/books', 'POST', content: json_encode($payload, JSON_THROW_ON_ERROR));
$request->headers->set('Content-Type', 'application/json');

// Act
$response = $kernel->handle($request);

// Assert
self::assertSame(201, $response->getStatusCode());
self::assertStringContainsString('no-cache', (string) $response->headers->get('Cache-Control'));
self::assertStringContainsString('must-revalidate', (string) $response->headers->get('Cache-Control'));
}

#[WithoutErrorHandler]
public function testUnknownApiPathReturnsProblemJson(): void
{
Expand Down
93 changes: 93 additions & 0 deletions tests/Unit/Controller/CommandControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,99 @@ public function testInvokeThrowsApiProblemExceptionWhenValidationFails(): void
}
}

public function testInvokeSetsDefaultCacheControlHeader(): void
{
// Arrange
$command = new ExampleCommand();
$request = new Request();

$validator = $this->createMock(ValidatorInterface::class);
$violations = $this->createMock(ConstraintViolationListInterface::class);
$violations->method('count')->willReturn(0);
$validator->method('validate')->willReturn($violations);

$result = ['ok' => true];
$envelope = new Envelope($command, [new HandledStamp($result, 'handler')]);

$messageBus = $this->createMock(MessageBusInterface::class);
$messageBus->method('dispatch')->willReturn($envelope);

$statusResolver = $this->createMock(StatusResolverInterface::class);
$statusResolver->method('resolve')->willReturn(200);

$responder = $this->createMock(ResponderInterface::class);
$responder->method('respond')->willReturn(new Response((string) json_encode($result), 200));

// Act
$controller = new CommandController($messageBus, $validator, $statusResolver, $responder, new WrappedExceptionUnwrapper());
$response = $controller($request, $command);

// Assert — Symfony's ResponseHeaderBag appends 'private' when no 'public' directive is present
self::assertStringContainsString('no-store', (string) $response->headers->get('Cache-Control'));
}

public function testInvokeOmitsCacheControlHeaderWhenDisabled(): void
{
// Arrange
$command = new ExampleCommand();
$request = new Request();

$validator = $this->createMock(ValidatorInterface::class);
$violations = $this->createMock(ConstraintViolationListInterface::class);
$violations->method('count')->willReturn(0);
$validator->method('validate')->willReturn($violations);

$result = ['ok' => true];
$envelope = new Envelope($command, [new HandledStamp($result, 'handler')]);

$messageBus = $this->createMock(MessageBusInterface::class);
$messageBus->method('dispatch')->willReturn($envelope);

$statusResolver = $this->createMock(StatusResolverInterface::class);
$statusResolver->method('resolve')->willReturn(200);

$responder = $this->createMock(ResponderInterface::class);
$responder->method('respond')->willReturn(new Response((string) json_encode($result), 200));

// Act
$controller = new CommandController($messageBus, $validator, $statusResolver, $responder, new WrappedExceptionUnwrapper(), cacheControl: null);
$response = $controller($request, $command);

// Assert — Symfony sets a computed default; the controller must not override it
self::assertStringNotContainsString('no-store', (string) $response->headers->get('Cache-Control'));
}

public function testInvokeSetsCustomCacheControlHeader(): void
{
// Arrange
$command = new ExampleCommand();
$request = new Request();

$validator = $this->createMock(ValidatorInterface::class);
$violations = $this->createMock(ConstraintViolationListInterface::class);
$violations->method('count')->willReturn(0);
$validator->method('validate')->willReturn($violations);

$result = ['ok' => true];
$envelope = new Envelope($command, [new HandledStamp($result, 'handler')]);

$messageBus = $this->createMock(MessageBusInterface::class);
$messageBus->method('dispatch')->willReturn($envelope);

$statusResolver = $this->createMock(StatusResolverInterface::class);
$statusResolver->method('resolve')->willReturn(200);

$responder = $this->createMock(ResponderInterface::class);
$responder->method('respond')->willReturn(new Response((string) json_encode($result), 200));

// Act
$controller = new CommandController($messageBus, $validator, $statusResolver, $responder, new WrappedExceptionUnwrapper(), cacheControl: 'no-cache, private');
$response = $controller($request, $command);

// Assert
self::assertSame('no-cache, private', $response->headers->get('Cache-Control'));
}

public function testInvokeRethrowsPreviousExceptionFromHandlerFailedException(): void
{
// Arrange
Expand Down
2 changes: 2 additions & 0 deletions tests/Unit/DependencyInjection/ConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public function testDefaultConfig(): void
'enabled' => true,
'groups' => ['Default'],
],
'cache_control' => 'no-store',
'openapi' => [
'problem_details' => true,
],
Expand Down Expand Up @@ -62,6 +63,7 @@ public function testCustomConfig(): void
'enabled' => false,
'groups' => ['Custom', 'Special'],
],
'cache_control' => 'no-store',
'openapi' => [
'problem_details' => true,
],
Expand Down
Loading