bug #32206 Catch JsonException and rethrow in JsonEncode (phil-davis)

This PR was merged into the 3.4 branch.

Discussion
----------

Catch JsonException and rethrow in JsonEncode

| Q             | A
| ------------- | ---
| Branch?       | 3.4
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | adjustment to implementation of previous PRs for issue #31447
| License       | MIT
| Doc PR        | not applicable

PR #31860 provided handling of PHP  7.3 `JSON_THROW_ON_ERROR` behavior in the various `JsonEncode` and related classes/methods.

PR #31869 adjusted that. In particular, it adjusted ` src/Symfony/Component/Serializer/Encoder/JsonDecode.php` so that it catches any `JsonException` and re-throws it as `NotEncodableValueException`. That preserves the previous behavior of `JsonDecode:decode` - it always throws `NotEncodableValueException` when something goes wrong.

IMO `JsonEncode:encode` needs the same logic. At the moment, if a caller specifies `JSON_THROW_ON_ERROR` then the method can throw `JsonException`, but actually the "standard" for `JsonEncode:encode` is that it throws `NotEncodableValueException`

Adjust `JsonEncode:encode` to catch `JsonException` and rethrow it as `NotEncodableValueException`

Commits
-------

9c76790ee8 Catch JsonException and rethrow in JsonEncode
This commit is contained in:
Nicolas Grekas 2019-06-28 13:57:22 +02:00
commit 2bab37d64f
1 changed files with 8 additions and 3 deletions

View File

@ -35,14 +35,19 @@ class JsonEncode implements EncoderInterface
public function encode($data, $format, array $context = [])
{
$context = $this->resolveContext($context);
$options = $context['json_encode_options'];
$encodedJson = json_encode($data, $context['json_encode_options']);
try {
$encodedJson = json_encode($data, $options);
} catch (\JsonException $e) {
throw new NotEncodableValueException($e->getMessage(), 0, $e);
}
if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $context['json_encode_options'])) {
if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $options)) {
return $encodedJson;
}
if (JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($context['json_encode_options'] & JSON_PARTIAL_OUTPUT_ON_ERROR))) {
if (JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($options & JSON_PARTIAL_OUTPUT_ON_ERROR))) {
throw new NotEncodableValueException(json_last_error_msg());
}