You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
feature #42297 [Serializer] Add support for serializing empty array as object (lyrixx)
This PR was merged into the 5.4 branch.
Discussion
----------
[Serializer] Add support for serializing empty array as object
| Q | A
| ------------- | ---
| Branch? | 5.4
| Bug fix? | yes (fix a new feature)
| New feature? | yes (fix a new feature)
| Deprecations? | no
| Tickets | Fix#42282
| License | MIT
| Doc PR | symfony/symfony-docs#15554
---
New usage:
```php
public function __construct(
#[Context([Serializer::EMPTY_ARRAY_AS_OBJECT => true ])]
public array $mapWithOption = [],
#[Context([Serializer::EMPTY_ARRAY_AS_OBJECT => true ])]
public array $mapWithOptionAndData = ['foo' => 'bar'],
public array $mapWithoutOption = [],
public array $mapWithoutOptionAndData = ['foo' => 'bar'],
) {
}
```
=>
```
{"mapWithOption":{},"mapWithOptionAndData":{"foo":"bar"},"mapWithoutOption":[],"mapWithoutOptionAndData":{"foo":"bar"}}
```
Commits
-------
c940b74 [Serializer] Add support for serializing empty array as object
case ($context[AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS] ?? false) && is_object($data):
171
+
return$data;
172
+
case ($context[self::EMPTY_ARRAYS_AS_OBJECT] ?? false) && is_array($data):
173
+
returnnew \ArrayObject();
174
+
}
164
175
}
165
176
166
177
$normalized = [];
@@ -179,7 +190,7 @@ public function normalize($data, string $format = null, array $context = [])
179
190
thrownewNotNormalizableValueException(sprintf('Could not normalize object of type "%s", no supporting normalizer found.', get_debug_type($data)));
180
191
}
181
192
182
-
thrownewNotNormalizableValueException('An unexpected value could not be normalized: '.(!\is_resource($data) ? var_export($data, true) : sprintf('%s resource', get_resource_type($data))));
193
+
thrownewNotNormalizableValueException('An unexpected value could not be normalized: '.(!\is_resource($data) ? var_export($data, true) : sprintf('"%s" resource', get_resource_type($data))));
0 commit comments