Skip to content

Support "Allow" header for 405 errors #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
18 changes: 17 additions & 1 deletion src/ErrorFormatter/AbstractFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,13 @@ public function handle(Throwable $error, ServerRequestInterface $request): Respo
$response = $this->responseFactory->createResponse($this->errorStatus($error));
$body = $this->streamFactory->createStream($this->format($error, $contentType));

return $response->withBody($body)->withHeader('Content-Type', $contentType);
$response = $response->withBody($body)->withHeader('Content-Type', $contentType);

if (405 == $response->getStatusCode() && $allow = $this->allow($error)) {
$response = $response->withHeader('Allow', implode(', ', $allow));
}

return $response;
}

protected function errorStatus(Throwable $error): int
Expand All @@ -59,6 +65,16 @@ protected function errorStatus(Throwable $error): int
return 500;
}

protected function allow(Throwable $error): ?array
{
if (method_exists($error, 'getContext')) {
$context = $error->getContext();
return isset($context['allow']) ? (array) $context['allow'] : null;
}

return null;
}

protected function getContentType(ServerRequestInterface $request): ?string
{
$accept = $request->getHeaderLine('Accept');
Expand Down
22 changes: 22 additions & 0 deletions tests/ErrorHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,28 @@ public function getStatusCode(): int
$this->assertEquals(418, $response->getStatusCode());
}

public function testNotAllowedException()
{
$response = Dispatcher::run([
new ErrorHandler(),
function ($request) {
throw new class() extends Exception {
public function getStatusCode(): int
{
return 405;
}
public function getContext(): array
{
return ['allow' => ['GET', 'POST']];
}
};
},
]);

$this->assertEquals(405, $response->getStatusCode());
$this->assertEquals('GET, POST', $response->getHeaderLine('Allow'));
}

public function testGifFormatter()
{
$request = Factory::createServerRequest('GET', '/');
Expand Down
Loading