Skip to content

Commit

Permalink
Merge pull request #169 from WoltLab/json-response-error
Browse files Browse the repository at this point in the history
Correctly handle explicitly providing `JSON_THROW_ON_ERROR` in `JsonResponse`
  • Loading branch information
Ocramius authored Aug 1, 2023
2 parents f6defb0 + cdf1a30 commit 283cdc5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
17 changes: 7 additions & 10 deletions src/Response/JsonResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,21 @@

namespace Laminas\Diactoros\Response;

use JsonException;
use Laminas\Diactoros\Exception;
use Laminas\Diactoros\Response;
use Laminas\Diactoros\Stream;

use function is_object;
use function is_resource;
use function json_encode;
use function json_last_error;
use function json_last_error_msg;
use function sprintf;

use const JSON_ERROR_NONE;
use const JSON_HEX_AMP;
use const JSON_HEX_APOS;
use const JSON_HEX_QUOT;
use const JSON_HEX_TAG;
use const JSON_THROW_ON_ERROR;
use const JSON_UNESCAPED_SLASHES;

/**
Expand Down Expand Up @@ -131,17 +130,15 @@ private function jsonEncode(mixed $data, int $encodingOptions): string
// Clear json_last_error()
json_encode(null);

$json = json_encode($data, $encodingOptions);

if (JSON_ERROR_NONE !== json_last_error()) {
try {
return json_encode($data, $encodingOptions | JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
throw new Exception\InvalidArgumentException(sprintf(
'Unable to encode data to JSON in %s: %s',
self::class,
json_last_error_msg()
));
$e->getMessage()
), 0, $e);
}

return $json;
}

private function setPayload(mixed $data): void
Expand Down
17 changes: 17 additions & 0 deletions test/Response/JsonResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use const JSON_HEX_QUOT;
use const JSON_HEX_TAG;
use const JSON_PRETTY_PRINT;
use const JSON_THROW_ON_ERROR;
use const JSON_UNESCAPED_SLASHES;

class JsonResponseTest extends TestCase
Expand Down Expand Up @@ -103,6 +104,22 @@ public function testJsonErrorHandlingOfBadEmbeddedData(): void
new JsonResponse($data);
}

public function testJsonErrorHandlingOfMalformedUtf8(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Unable to encode');

new JsonResponse("\xff");
}

public function testJsonErrorHandlingOfMalformedUtf8IfExplicitlySettingThrowFlag(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Unable to encode');

new JsonResponse("\xff", encodingOptions: JsonResponse::DEFAULT_JSON_FLAGS | JSON_THROW_ON_ERROR);
}

/** @return non-empty-array<non-empty-string, array{non-empty-string, non-empty-string}> */
public function valuesToJsonEncode(): array
{
Expand Down

0 comments on commit 283cdc5

Please sign in to comment.