Skip to content

Commit

Permalink
fix: properly encode scalar value in JSON normalization
Browse files Browse the repository at this point in the history
  • Loading branch information
romm committed Mar 12, 2024
1 parent 1b8efa1 commit 2107ea1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
12 changes: 4 additions & 8 deletions src/Normalizer/Formatter/JsonFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,14 @@
use CuyZ\Valinor\Normalizer\Formatter\Exception\CannotFormatInvalidTypeToJson;
use Generator;

use function addcslashes;
use function array_is_list;
use function fwrite;
use function is_array;
use function is_bool;
use function is_float;
use function is_int;
use function is_iterable;
use function is_null;
use function is_string;
use function is_scalar;
use function json_encode;

/** @internal */
final class JsonFormatter implements StreamFormatter
Expand All @@ -34,10 +32,8 @@ public function format(mixed $value): void
$this->write('null');
} elseif (is_bool($value)) {
$this->write($value ? 'true' : 'false');
} elseif (is_int($value) || is_float($value)) {
$this->write((string)$value);
} elseif (is_string($value)) {
$this->write('"' . addcslashes($value, '"') . '"');
} elseif (is_scalar($value)) {
$this->write(json_encode($value, JSON_THROW_ON_ERROR));
} elseif (is_iterable($value)) {
// Note: when a generator is formatted, it is considered as a list
// if its first key is 0. This is done early because the first JSON
Expand Down
10 changes: 8 additions & 2 deletions tests/Integration/Normalizer/NormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ public static function normalize_basic_values_yields_expected_output_data_provid
'expected json' => 'true',
];

yield 'class string' => [
'input' => 'Some\Namespace\To\Class',
'expected array' => 'Some\Namespace\To\Class',
'expected json' => '"Some\\\\Namespace\\\\To\\\\Class"',
];

yield 'array of scalar' => [
'input' => [
'string' => 'foo',
Expand Down Expand Up @@ -295,7 +301,7 @@ public function getIterator(): Traversable
yield 'time zone with default transformer' => [
'input' => new DateTimeZone('Europe/Paris'),
'expected array' => 'Europe/Paris',
'expected json' => '"Europe/Paris"',
'expected json' => '"Europe\/Paris"',
];

yield 'time zone with transformer' => [
Expand All @@ -304,7 +310,7 @@ public function getIterator(): Traversable
'name' => 'Europe/Paris',
'country_code' => 'FR',
],
'expected json' => '{"name":"Europe/Paris","country_code":"FR"}',
'expected json' => '{"name":"Europe\/Paris","country_code":"FR"}',
'transformers' => [
[fn (DateTimeZone $object) => [
'name' => $object->getName(),
Expand Down

0 comments on commit 2107ea1

Please sign in to comment.