diff --git a/src/Constrict/ConstrictResponse.php b/src/Constrict/ConstrictResponse.php index c6e9a89..9d54960 100644 --- a/src/Constrict/ConstrictResponse.php +++ b/src/Constrict/ConstrictResponse.php @@ -97,7 +97,8 @@ class ConstrictResponse extends Message implements ResponseInterface */ public function json(array $content, int $statusCode = 200): static { - $this->stream->write(json_encode($content, JSON_UNESCAPED_UNICODE)); + $encoded = json_encode($content, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE); + $this->stream->write($encoded === false ? '{"error":"json encode failed"}' : $encoded); return $this->withContentType(ContentType::JSON)->withStatus($statusCode); } diff --git a/src/Format/ArrayFormat.php b/src/Format/ArrayFormat.php index 701191b..3173877 100644 --- a/src/Format/ArrayFormat.php +++ b/src/Format/ArrayFormat.php @@ -25,7 +25,8 @@ class ArrayFormat implements IFormat */ public function call($result): ResponseInterface { - return $this->response->withBody(new Stream(json_encode($result, JSON_UNESCAPED_UNICODE))); + $encoded = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE); + return $this->response->withBody(new Stream($encoded === false ? '[]' : $encoded)); } diff --git a/src/Format/MixedFormat.php b/src/Format/MixedFormat.php index 72e364b..a711f82 100644 --- a/src/Format/MixedFormat.php +++ b/src/Format/MixedFormat.php @@ -31,7 +31,8 @@ class MixedFormat implements IFormat return $this->response->withBody(new Stream('[object]')); } if (is_array($result)) { - return $this->response->withBody(new Stream(json_encode($result, JSON_UNESCAPED_UNICODE))); + $encoded = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE); + return $this->response->withBody(new Stream($encoded === false ? '[]' : $encoded)); } else { return $this->response->withBody(new Stream((string)$result)); }