Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d3c5055

Browse files
dunglasnicolas-grekas
authored andcommitted
[Serializer] Add an option to skip null values
1 parent 9610d10 commit d3c5055

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

src/Symfony/Component/Serializer/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ CHANGELOG
44
4.2.0
55
-----
66

7+
* added a `skip_null_values` context option to not serialize properties with a `null` values
78
* `AbstractNormalizer::handleCircularReference` is now final and receives
89
two optional extra arguments: the format and the context
910
* added support for XML comment encoding (encoding `['#comment' => ' foo ']` results `<!-- foo -->`)

src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
3535
const ENABLE_MAX_DEPTH = 'enable_max_depth';
3636
const DEPTH_KEY_PATTERN = 'depth_%s::%s';
3737
const DISABLE_TYPE_ENFORCEMENT = 'disable_type_enforcement';
38+
const SKIP_NULL_VALUES = 'skip_null_values';
3839

3940
private $propertyTypeExtractor;
4041
private $typesCache = array();
@@ -402,6 +403,10 @@ private function getTypes(string $currentClass, string $attribute)
402403
*/
403404
private function updateData(array $data, string $attribute, $attributeValue, string $class, ?string $format, array $context): array
404405
{
406+
if (null === $attributeValue && ($context[self::SKIP_NULL_VALUES] ?? false)) {
407+
return $data;
408+
}
409+
405410
if ($this->nameConverter) {
406411
$attribute = $this->nameConverter->normalize($attribute, $class, $format, $context);
407412
}

src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,16 @@ public function testExtraAttributesException()
161161
'allow_extra_attributes' => false,
162162
));
163163
}
164+
165+
public function testSkipNullValues()
166+
{
167+
$dummy = new Dummy();
168+
$dummy->bar = 'present';
169+
170+
$normalizer = new ObjectNormalizer();
171+
$result = $normalizer->normalize($dummy, null, array(AbstractObjectNormalizer::SKIP_NULL_VALUES => true));
172+
$this->assertSame(array('bar' => 'present'), $result);
173+
}
164174
}
165175

166176
class AbstractObjectNormalizerDummy extends AbstractObjectNormalizer

0 commit comments

Comments
 (0)