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 5, 2023
1 parent 7bc4988 commit 875df76
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 @@ -187,9 +187,13 @@ function csrf_input(string $instance = 'default') : string
*/
function 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 @@ -134,15 +134,43 @@ public function testNotFound() : void
self::assertInstanceOf(Response::class, $response);
self::assertStringContainsString('404', $response->getBody());
self::assertSame(404, $response->getStatusCode());
self::assertNull($response->getHeader('Content-Type'));
}

public function testNotFoundJson() : void
public function testNotFoundWithContentTypeJson() : void
{
$_SERVER['HTTP_CONTENT_TYPE'] = 'application/json';
$response = 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 testNotFoundWithAcceptJson() : void
{
$_SERVER['HTTP_ACCEPT'] = 'application/json';
$response = 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 testNotFoundWithAcceptHtml() : void
{
$_SERVER['HTTP_ACCEPT'] = 'text/html';
$response = 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 875df76

Please sign in to comment.