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
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,47 @@ Outside the window, the endpoint works normally with deprecation headers.

If `response_on_sunset` is enabled (default), the endpoint permanently returns `410 Gone` once the sunset date has passed.

## Customizing the error response

Two Symfony events are dispatched before the default `410 Gone` response is returned:

- `ApiSunsetEvent` — dispatched when the sunset date has passed
- `ApiBrownoutEvent` — dispatched during a brownout window

An event listener can call `$event->setResponse()` to replace the default 410 with a custom response. Both events expose the `ApiDeprecated` attribute and the deprecation headers that will be added to the response.

### Example: returning a Problem Details response (RFC 9457)

```php
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\JsonResponse;
use Tiime\ApiDeprecationBundle\Event\ApiBrownoutEvent;
use Tiime\ApiDeprecationBundle\Event\ApiSunsetEvent;

#[AsEventListener]
final class DeprecationProblemDetailsListener
{
public function __invoke(ApiSunsetEvent|ApiBrownoutEvent $event): void
{
$response = new JsonResponse([
'type' => 'https://docs.example.com/errors/gone',
'title' => 'Gone',
'status' => 410,
'detail' => sprintf(
'This endpoint was deprecated on %s and is no longer available.',
$event->attribute->since,
),
], 410, ['Content-Type' => 'application/problem+json']);

$event->setResponse($response);
}
}
```

The `$event->headers` array contains the computed deprecation headers (`Deprecation`, `Sunset`, `Link`, `Retry-After`) — they are automatically added to whatever response is returned.

If no listener sets a response, the default `410 Gone` with a plain-text body is returned (backward compatible).

## Attribute parameters

| Parameter | Type | Default | Description |
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"dragonmantank/cron-expression": "^3.3",
"symfony/config": "^6.4|^7.0|^8.0",
"symfony/dependency-injection": "^6.4|^7.0|^8.0",
"symfony/event-dispatcher-contracts": "^3.0",
"symfony/http-kernel": "^6.4|^7.0|^8.0"
},
"require-dev": {
Expand Down
1 change: 1 addition & 0 deletions src/ApiDeprecationBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ public function loadExtension(array $config, ContainerConfigurator $container, C
$config['response_on_sunset'],
$builder->has('logger') ? service('logger') : null,
$builder->has('clock') ? service('clock') : null,
service('event_dispatcher')->nullOnInvalid(),
])
->tag('kernel.event_subscriber')
;
Expand Down
9 changes: 9 additions & 0 deletions src/Event/ApiBrownoutEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace Tiime\ApiDeprecationBundle\Event;

final class ApiBrownoutEvent extends ApiDeprecationEvent
{
}
32 changes: 32 additions & 0 deletions src/Event/ApiDeprecationEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace Tiime\ApiDeprecationBundle\Event;

use Symfony\Component\HttpFoundation\Response;
use Tiime\ApiDeprecationBundle\Attribute\ApiDeprecated;

abstract class ApiDeprecationEvent
{
private ?Response $response = null;

/**
* @param array<string, string> $headers
*/
public function __construct(
public readonly ApiDeprecated $attribute,
public readonly array $headers,
) {
}

public function getResponse(): ?Response
{
return $this->response;
}

public function setResponse(Response $response): void
{
$this->response = $response;
}
}
9 changes: 9 additions & 0 deletions src/Event/ApiSunsetEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace Tiime\ApiDeprecationBundle\Event;

final class ApiSunsetEvent extends ApiDeprecationEvent
{
}
51 changes: 51 additions & 0 deletions src/EventListener/DeprecationHeaderListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@
namespace Tiime\ApiDeprecationBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\Exception\GoneHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Psr\Clock\ClockInterface;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Tiime\ApiDeprecationBundle\Attribute\ApiDeprecated;
use Tiime\ApiDeprecationBundle\Attribute\ApiDeprecatedResolver;
use Tiime\ApiDeprecationBundle\Brownout\BrownoutChecker;
use Tiime\ApiDeprecationBundle\Event\ApiBrownoutEvent;
use Tiime\ApiDeprecationBundle\Event\ApiSunsetEvent;
use Tiime\ApiDeprecationBundle\Header\HeaderBuilder;

final class DeprecationHeaderListener implements EventSubscriberInterface
Expand All @@ -24,6 +28,7 @@
private readonly bool $responseOnSunset,
private readonly ?LoggerInterface $logger = null,
private readonly ?ClockInterface $clock = null,
private readonly ?EventDispatcherInterface $eventDispatcher = null,
Comment thread
rflavien marked this conversation as resolved.
Resolved
) {
}

Expand Down Expand Up @@ -59,6 +64,14 @@
if ($this->responseOnSunset && $sunsetPassed) {
$this->logger?->notice('Sunset endpoint called, returning 410 Gone.', ['sunset' => $attribute->sunset]);

$customResponse = $this->dispatchSunsetEvent($attribute, $headers);

if ($customResponse !== null) {
$event->setController(static fn () => $customResponse);

return;
}

throw new GoneHttpException(
'This endpoint has been removed.',
headers: $headers,
Expand All @@ -82,6 +95,14 @@

$this->logger?->warning('Brownout active, returning 410 Gone.', ['brownout' => $attribute->brownout, 'sunset' => $attribute->sunset]);

$customResponse = $this->dispatchBrownoutEvent($attribute, $headers);

if ($customResponse !== null) {
$event->setController(static fn () => $customResponse);

return;
}

throw new GoneHttpException(
'This endpoint is deprecated and currently unavailable (brownout).',
headers: $headers,
Expand Down Expand Up @@ -114,13 +135,43 @@
}
}

/**
* @param array<string, string> $headers
*/
private function dispatchSunsetEvent(ApiDeprecated $attribute, array $headers): ?Response
{
if ($this->eventDispatcher === null) {
return null;
}

$sunsetEvent = new ApiSunsetEvent($attribute, $headers);
$this->eventDispatcher->dispatch($sunsetEvent);

return $sunsetEvent->getResponse();
}

/**
* @param array<string, string> $headers
*/
private function dispatchBrownoutEvent(ApiDeprecated $attribute, array $headers): ?Response
{
if ($this->eventDispatcher === null) {
return null;
}

$brownoutEvent = new ApiBrownoutEvent($attribute, $headers);
$this->eventDispatcher->dispatch($brownoutEvent);

return $brownoutEvent->getResponse();
}

private function resolveAttribute(ControllerEvent $event): ?ApiDeprecated
{
$controller = $event->getController();

if (\is_array($controller) && isset($controller[0], $controller[1]) && \is_object($controller[0]) && \is_string($controller[1])) {

Check warning on line 172 in src/EventListener/DeprecationHeaderListener.php

View workflow job for this annotation

GitHub Actions / Mutation Testing

Escaped Mutant for Mutator "DecrementInteger": @@ @@ { $controller = $event->getController(); - if (\is_array($controller) && isset($controller[0], $controller[1]) && \is_object($controller[0]) && \is_string($controller[1])) { + if (\is_array($controller) && isset($controller[0], $controller[0]) && \is_object($controller[0]) && \is_string($controller[1])) { $reflection = new \ReflectionMethod($controller[0], $controller[1]); } elseif (\is_object($controller) && method_exists($controller, '__invoke')) { $reflection = new \ReflectionMethod($controller, '__invoke');

Check warning on line 172 in src/EventListener/DeprecationHeaderListener.php

View workflow job for this annotation

GitHub Actions / Mutation Testing

Escaped Mutant for Mutator "IncrementInteger": @@ @@ { $controller = $event->getController(); - if (\is_array($controller) && isset($controller[0], $controller[1]) && \is_object($controller[0]) && \is_string($controller[1])) { + if (\is_array($controller) && isset($controller[1], $controller[1]) && \is_object($controller[0]) && \is_string($controller[1])) { $reflection = new \ReflectionMethod($controller[0], $controller[1]); } elseif (\is_object($controller) && method_exists($controller, '__invoke')) { $reflection = new \ReflectionMethod($controller, '__invoke');
$reflection = new \ReflectionMethod($controller[0], $controller[1]);
} elseif (\is_object($controller) && method_exists($controller, '__invoke')) {

Check warning on line 174 in src/EventListener/DeprecationHeaderListener.php

View workflow job for this annotation

GitHub Actions / Mutation Testing

Escaped Mutant for Mutator "LogicalAnd": @@ @@ if (\is_array($controller) && isset($controller[0], $controller[1]) && \is_object($controller[0]) && \is_string($controller[1])) { $reflection = new \ReflectionMethod($controller[0], $controller[1]); - } elseif (\is_object($controller) && method_exists($controller, '__invoke')) { + } elseif (\is_object($controller) || method_exists($controller, '__invoke')) { $reflection = new \ReflectionMethod($controller, '__invoke'); } else { return null;
$reflection = new \ReflectionMethod($controller, '__invoke');
} else {
return null;
Expand Down
116 changes: 116 additions & 0 deletions tests/EventListener/DeprecationHeaderListenerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Tiime\ApiDeprecationBundle\Attribute\ApiDeprecated;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
Comment thread
rflavien marked this conversation as resolved.
Resolved
use Tiime\ApiDeprecationBundle\Brownout\BrownoutChecker;
use Tiime\ApiDeprecationBundle\Event\ApiBrownoutEvent;
use Tiime\ApiDeprecationBundle\Event\ApiSunsetEvent;
use Tiime\ApiDeprecationBundle\EventListener\DeprecationHeaderListener;
use Tiime\ApiDeprecationBundle\Header\HeaderBuilder;

Expand Down Expand Up @@ -481,6 +484,119 @@ public function __invoke(): void {}
}
}

public function testSunsetEventDispatchedWithCustomResponse(): void
{
$checker = $this->createBrownoutChecker(false);
$customResponse = new Response('{"error": "gone"}', Response::HTTP_GONE, ['Content-Type' => 'application/json']);

$dispatcher = $this->createMock(EventDispatcherInterface::class);
$dispatcher->expects(self::once())
->method('dispatch')
->with(self::isInstanceOf(ApiSunsetEvent::class))
->willReturnCallback(function (ApiSunsetEvent $event) use ($customResponse) {
$event->setResponse($customResponse);

return $event;
});

$listener = new DeprecationHeaderListener($this->headerBuilder, $checker, true, eventDispatcher: $dispatcher);

$controller = new #[ApiDeprecated(sunset: '2020-01-01')] class {
public function __invoke(): void {}
};

$request = new Request();
$kernel = $this->createMock(HttpKernelInterface::class);
$event = new ControllerEvent($kernel, $controller, $request, HttpKernelInterface::MAIN_REQUEST);

$listener->onKernelController($event);

// Controller should have been replaced
$result = ($event->getController())();
self::assertSame($customResponse, $result);
}

public function testSunsetEventFallsBackToExceptionWhenNoResponseSet(): void
{
$checker = $this->createBrownoutChecker(false);

$dispatcher = $this->createMock(EventDispatcherInterface::class);
$dispatcher->expects(self::once())
->method('dispatch')
->with(self::isInstanceOf(ApiSunsetEvent::class));

$listener = new DeprecationHeaderListener($this->headerBuilder, $checker, true, eventDispatcher: $dispatcher);

$controller = new #[ApiDeprecated(sunset: '2020-01-01')] class {
public function __invoke(): void {}
};

$request = new Request();
$kernel = $this->createMock(HttpKernelInterface::class);
$event = new ControllerEvent($kernel, $controller, $request, HttpKernelInterface::MAIN_REQUEST);

$this->expectException(GoneHttpException::class);
$this->expectExceptionMessage('removed');

$listener->onKernelController($event);
}

public function testBrownoutEventDispatchedWithCustomResponse(): void
{
$checker = $this->createBrownoutChecker(true);
$customResponse = new Response('{"error": "brownout"}', Response::HTTP_GONE, ['Content-Type' => 'application/json']);

$dispatcher = $this->createMock(EventDispatcherInterface::class);
$dispatcher->expects(self::once())
->method('dispatch')
->with(self::isInstanceOf(ApiBrownoutEvent::class))
->willReturnCallback(function (ApiBrownoutEvent $event) use ($customResponse) {
$event->setResponse($customResponse);

return $event;
});

$listener = new DeprecationHeaderListener($this->headerBuilder, $checker, false, eventDispatcher: $dispatcher);

$controller = new #[ApiDeprecated(since: '2024-06-01', sunset: '2030-01-01', brownout: 'progressive')] class {
public function __invoke(): void {}
};

$request = new Request();
$kernel = $this->createMock(HttpKernelInterface::class);
$event = new ControllerEvent($kernel, $controller, $request, HttpKernelInterface::MAIN_REQUEST);

$listener->onKernelController($event);

$result = ($event->getController())();
self::assertSame($customResponse, $result);
}

public function testBrownoutEventFallsBackToExceptionWhenNoResponseSet(): void
{
$checker = $this->createBrownoutChecker(true);

$dispatcher = $this->createMock(EventDispatcherInterface::class);
$dispatcher->expects(self::once())
->method('dispatch')
->with(self::isInstanceOf(ApiBrownoutEvent::class));

$listener = new DeprecationHeaderListener($this->headerBuilder, $checker, false, eventDispatcher: $dispatcher);

$controller = new #[ApiDeprecated(since: '2024-06-01', sunset: '2030-01-01', brownout: 'progressive')] class {
public function __invoke(): void {}
};

$request = new Request();
$kernel = $this->createMock(HttpKernelInterface::class);
$event = new ControllerEvent($kernel, $controller, $request, HttpKernelInterface::MAIN_REQUEST);

$this->expectException(GoneHttpException::class);
$this->expectExceptionMessage('brownout');

$listener->onKernelController($event);
}

private function createBrownoutChecker(bool $inWindow): BrownoutChecker&\PHPUnit\Framework\MockObject\MockObject
{
$checker = $this->createMock(BrownoutChecker::class);
Expand Down
Loading