Skip to content

Commit

Permalink
feat: add support for JSON_FORCE_OBJECT option in json normalizer
Browse files Browse the repository at this point in the history
  • Loading branch information
romm committed Jul 19, 2024
1 parent 119df34 commit c286867
Showing 1 changed file with 5 additions and 8 deletions.
13 changes: 5 additions & 8 deletions src/Normalizer/Formatter/JsonFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,6 @@ public function format(mixed $value): void
*/
$this->write(json_encode($value, $this->jsonEncodingOptions));
} 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
Expand All @@ -58,8 +52,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;

Expand Down

0 comments on commit c286867

Please sign in to comment.