From aa2651c44d0e66b0ff917225a41d63fde121ac4e Mon Sep 17 00:00:00 2001 From: NeoIsRecursive Date: Mon, 6 Jul 2026 15:29:23 +0200 Subject: [PATCH] fix: use tempests `Json\encode` function to throw when sending unserializable values --- packages/router/src/GenericResponseSender.php | 2 +- .../Http/GenericResponseSenderTest.php | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/router/src/GenericResponseSender.php b/packages/router/src/GenericResponseSender.php index be9f1f4c8..e00b81da8 100644 --- a/packages/router/src/GenericResponseSender.php +++ b/packages/router/src/GenericResponseSender.php @@ -104,7 +104,7 @@ private function sendContent(Response $response): void if ($response instanceof File || $response instanceof Download) { readfile($body); } elseif (is_array($body) || $body instanceof JsonSerializable) { - echo json_encode($body); + echo Json\encode($body); } elseif ($body instanceof View) { $this->renderView($response); } else { diff --git a/tests/Integration/Http/GenericResponseSenderTest.php b/tests/Integration/Http/GenericResponseSenderTest.php index 6ac123250..27d0b51bb 100644 --- a/tests/Integration/Http/GenericResponseSenderTest.php +++ b/tests/Integration/Http/GenericResponseSenderTest.php @@ -19,6 +19,7 @@ use Tempest\Http\ServerSentMessage; use Tempest\Http\Status; use Tempest\Router\GenericResponseSender; +use Tempest\Support\Json\Exception\JsonCouldNotBeEncoded; use Tempest\View\ViewRenderer; use Tests\Tempest\Integration\FrameworkIntegrationTestCase; @@ -117,6 +118,21 @@ public function test_sending_of_array_to_json(): void $this->assertSame('{"key":"value"}', $output); } + public function test_sending_invalid_json_throws_exception(): void + { + ob_start(); + $response = new GenericResponse( + status: Status::CREATED, + body: ['key' => "\xB1\x31"], + ); + + $responseSender = $this->container->get(GenericResponseSender::class); + + $this->assertException(JsonCouldNotBeEncoded::class, fn () => $responseSender->send($response)); + + ob_get_clean(); + } + public function test_sending_of_json_serializable_to_json(): void { ob_start();