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

Skip to content

Commit c76527b

Browse files
committed
Add a skipNullValues() method
1 parent 1a1024f commit c76527b

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

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

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,19 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
3737
const DISABLE_TYPE_ENFORCEMENT = 'disable_type_enforcement';
3838
const SKIP_NULL_VALUES = 'skip_null_values';
3939

40-
private $propertyTypeExtractor;
41-
private $typesCache = array();
42-
private $attributesCache = array();
43-
4440
/**
4541
* @var callable|null
4642
*/
47-
private $maxDepthHandler;
43+
protected $maxDepthHandler;
44+
45+
/**
46+
* @var bool
47+
*/
48+
protected $skipNullValues = false;
49+
50+
private $propertyTypeExtractor;
51+
private $typesCache = array();
52+
private $attributesCache = array();
4853

4954
/**
5055
* @var ClassDiscriminatorResolverInterface|null
@@ -221,6 +226,14 @@ public function setMaxDepthHandler(?callable $handler): void
221226
$this->maxDepthHandler = $handler;
222227
}
223228

229+
/**
230+
* Configures the normalizer to skip null values.
231+
*/
232+
public function skipNullValues()
233+
{
234+
$this->skipNullValues = true;
235+
}
236+
224237
/**
225238
* {@inheritdoc}
226239
*/
@@ -403,7 +416,7 @@ private function getTypes(string $currentClass, string $attribute)
403416
*/
404417
private function updateData(array $data, string $attribute, $attributeValue, string $class, ?string $format, array $context): array
405418
{
406-
if (null === $attributeValue && ($context[self::SKIP_NULL_VALUES] ?? false)) {
419+
if (null === $attributeValue && ($this->skipNullValues || ($context[self::SKIP_NULL_VALUES] ?? false))) {
407420
return $data;
408421
}
409422

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,10 @@ public function testSkipNullValues()
170170
$normalizer = new ObjectNormalizer();
171171
$result = $normalizer->normalize($dummy, null, array(AbstractObjectNormalizer::SKIP_NULL_VALUES => true));
172172
$this->assertSame(array('bar' => 'present'), $result);
173+
174+
$normalizer->skipNullValues();
175+
$result = $normalizer->normalize($dummy);
176+
$this->assertSame(array('bar' => 'present'), $result);
173177
}
174178
}
175179

0 commit comments

Comments
 (0)