From 0c34cdcc659b66fe3371c0ea307389c9818ef4a1 Mon Sep 17 00:00:00 2001 From: Romain Canon Date: Fri, 19 Jul 2024 17:23:50 +0200 Subject: [PATCH] feat: add support for `JSON_FORCE_OBJECT` option in json normalizer --- src/Normalizer/Formatter/JsonFormatter.php | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/Normalizer/Formatter/JsonFormatter.php b/src/Normalizer/Formatter/JsonFormatter.php index f97b3455..e7dfe298 100644 --- a/src/Normalizer/Formatter/JsonFormatter.php +++ b/src/Normalizer/Formatter/JsonFormatter.php @@ -46,12 +46,6 @@ public function format(mixed $value): void } elseif ($value instanceof EmptyObject) { $this->write('{}'); } elseif (is_iterable($value)) { - if ($value === [] && $this->jsonEncodingOptions & JSON_FORCE_OBJECT) { - $this->write('{}'); - - return; - - } // 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 // character for an array differs from the one for an object, and we @@ -61,8 +55,11 @@ public function format(mixed $value): void // afterward, this leads to a JSON array being written, while it // should have been an object. This is a trade-off we accept, // considering most generators starting at 0 are actually lists. - $isList = ($value instanceof Generator && $value->key() === 0) - || (is_array($value) && array_is_list($value)); + $isList = ! ($this->jsonEncodingOptions & JSON_FORCE_OBJECT) + && ( + ($value instanceof Generator && $value->key() === 0) + || (is_array($value) && array_is_list($value)) + ); $isFirst = true;