8000 [Serializer] Add an option to skip null values by dunglas · Pull Request #28661 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
4.2.0
-----

* added a `skip_null_values` context option to not serialize properties with a `null` values
* `AbstractNormalizer::handleCircularReference` is now final and receives
two optional extra arguments: the format and the context
* added support for XML comment encoding (encoding `['#comment' => ' foo ']` results `<!-- foo -->`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
const ENABLE_MAX_DEPTH = 'enable_max_depth';
const DEPTH_KEY_PATTERN = 'depth_%s::%s';
const DISABLE_TYPE_ENFORCEMENT = 'disable_type_enforcement';
const SKIP_NULL_VALUES = 'skip_null_values';

private $propertyTypeExtractor;
private $typesCache = array();
Expand Down Expand Up @@ -402,6 +403,10 @@ private function getTypes(string $currentClass, string $attribute)
*/
private function updateData(array $data, string $attribute, $attributeValue, string $class, ?string $format, array $context): array
{
if (null === $attributeValue && ($context[self::SKIP_NULL_VALUES] ?? false)) {
return $data;
}

if ($this->nameConverter) {
$attribute = $this->nameConverter->normalize($attribute, $class, $format, $context);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,16 @@ public function testExtraAttributesException()
'allow_extra_attributes' => false,
));
}

public function testSkipNullValues()
{
$dummy = new Dummy();
$dummy->bar = 'present';

$normalizer = new ObjectNormalizer();
$result = $normalizer->normalize($dummy, null, array(AbstractObjectNormalizer::SKIP_NULL_VALUES => true));
$this->assertSame(array('bar' => 'present'), $result);
}
}

class AbstractObjectNormalizerDummy extends AbstractObjectNormalizer
Expand Down
0