diff --git a/src/Router/Entities/JsonResponse.php b/src/Router/Entities/JsonResponse.php index 605212f..a70a9da 100644 --- a/src/Router/Entities/JsonResponse.php +++ b/src/Router/Entities/JsonResponse.php @@ -4,17 +4,18 @@ namespace Gacela\Router\Entities; +use function in_array; + final class JsonResponse extends Response { + /** + * @param list $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(); - } } diff --git a/tests/Feature/Router/RouterResponseTest.php b/tests/Feature/Router/RouterResponseTest.php index bc75fab..8a2c0d5 100644 --- a/tests/Feature/Router/RouterResponseTest.php +++ b/tests/Feature/Router/RouterResponseTest.php @@ -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()); + } }