Skip to content

Commit

Permalink
Allow negotiate JSON response
Browse files Browse the repository at this point in the history
  • Loading branch information
natanfelles committed Jul 4, 2023
1 parent 0c2cff8 commit 8c62a83
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
6 changes: 5 additions & 1 deletion boot/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,13 @@ function csrf_input(string $instance = 'default') : string
*/
function respond_not_found(array $variables = []) : Response
{
$request = App::request();
$response = App::response();
$response->setStatus(404);
if (App::request()->isJson()) {
if ($request->isJson() || $request->negotiateAccept([
'text/html',
'application/json',
]) === 'application/json') {
return $response->setJson([
'error' => [
'code' => 404,
Expand Down
30 changes: 29 additions & 1 deletion tests/boot/HelpersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -202,15 +202,43 @@ public function testRespondNotFound() : void
self::assertInstanceOf(Response::class, $response);
self::assertStringContainsString('404', $response->getBody());
self::assertSame(404, $response->getStatusCode());
self::assertNull($response->getHeader('Content-Type'));
}

public function testRespondNotFoundJson() : void
public function testRespondNotFoundWithContentTypeJson() : void
{
$_SERVER['HTTP_CONTENT_TYPE'] = 'application/json';
$response = respond_not_found();
self::assertInstanceOf(Response::class, $response);
self::assertStringContainsString('404', $response->getBody());
self::assertSame(404, $response->getStatusCode());
self::assertSame(
'application/json; charset=UTF-8',
$response->getHeader('Content-Type')
);
}

public function testRespondNotFoundWithAcceptJson() : void
{
$_SERVER['HTTP_ACCEPT'] = 'application/json';
$response = respond_not_found();
self::assertInstanceOf(Response::class, $response);
self::assertStringContainsString('404', $response->getBody());
self::assertSame(404, $response->getStatusCode());
self::assertSame(
'application/json; charset=UTF-8',
$response->getHeader('Content-Type')
);
}

public function testRespondNotFoundWithAcceptHtml() : void
{
$_SERVER['HTTP_ACCEPT'] = 'text/html';
$response = respond_not_found();
self::assertInstanceOf(Response::class, $response);
self::assertStringContainsString('404', $response->getBody());
self::assertSame(404, $response->getStatusCode());
self::assertNull($response->getHeader('Content-Type'));
}

public function testConfig() : void
Expand Down

0 comments on commit 8c62a83

Please sign in to comment.