Skip to content

Commit

Permalink
Avoid duplicated headers for JsonResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
Chemaclass committed Apr 22, 2023
1 parent 44e989d commit 0a24735
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
15 changes: 8 additions & 7 deletions src/Router/Entities/JsonResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@

namespace Gacela\Router\Entities;

use function in_array;

final class JsonResponse extends Response
{
/**
* @param list<string> $headers
*/
public function __construct(array $json, array $headers = [])
{
if (!in_array('Content-Type: application/json', $headers, true)) {
$headers[] = 'Content-Type: application/json';
}
parent::__construct(json_encode($json, JSON_THROW_ON_ERROR), $headers);
}

public function __toString(): string
{
header('Content-Type: application/json');

return parent::__toString();
}
}
28 changes: 28 additions & 0 deletions tests/Feature/Router/RouterResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,32 @@ public function test_response_headers(): void
],
], $this->headers());
}

public function test_json_response_headers(): void
{
$_SERVER['REQUEST_URI'] = 'https://example.org/uri';
$_SERVER['REQUEST_METHOD'] = Request::METHOD_GET;

Router::configure(static function (Routes $routes): void {
$routes->get('uri', static fn () => new JsonResponse(['key' => 'value'], [
'Access-Control-Allow-Origin: *',
'Content-Type: application/json',
]));
});

$this->expectOutputString('{"key":"value"}');

self::assertSame([
[
'header' => 'Access-Control-Allow-Origin: *',
'replace' => true,
'response_code' => 0,
],
[
'header' => 'Content-Type: application/json',
'replace' => true,
'response_code' => 0,
],
], $this->headers());
}
}

0 comments on commit 0a24735

Please sign in to comment.