[Serializer] Add an option to skip null values
This commit is contained in:
parent
9610d10034
commit
d3c5055f7b
@ -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 -->`)
|
||||
|
@ -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();
|
||||
@ -402,6 +403,10 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
@ -161,6 +161,16 @@ class AbstractObjectNormalizerTest extends TestCase
|
||||
'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
|
||||
|
Reference in New Issue
Block a user