Skip to content

Commit

Permalink
[Serializer] Fix normalization relying on allowed attributes only
Browse files Browse the repository at this point in the history
  • Loading branch information
mtarld authored and nicolas-grekas committed Nov 28, 2023
1 parent dcbfcb4 commit ca16751
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ protected function getAttributes(object $object, ?string $format, array $context
$allowedAttributes = $this->getAllowedAttributes($object, $context, true);

if (false !== $allowedAttributes) {
$attributes = array_intersect($attributes, $allowedAttributes);
$attributes = $attributes ? array_intersect($attributes, $allowedAttributes) : $allowedAttributes;
}

if ($context['cache_key'] && \stdClass::class !== $class) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -458,9 +458,39 @@ public function testNormalizeEmptyObject()
public function testNormalizeWithIgnoreAnnotationAndPrivateProperties()
{
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$serializer = new Serializer([new ObjectNormalizer($classMetadataFactory)]);
$normalizer = new ObjectNormalizer($classMetadataFactory);

$this->assertSame(['foo' => 'foo'], $serializer->normalize(new ObjectDummyWithIgnoreAnnotationAndPrivateProperty()));
$this->assertSame(['foo' => 'foo'], $normalizer->normalize(new ObjectDummyWithIgnoreAnnotationAndPrivateProperty()));
}

public function testNormalizeBasedOnAllowedAttributes()
{
$normalizer = new class() extends AbstractObjectNormalizer {
protected function getAllowedAttributes($classOrObject, array $context, bool $attributesAsString = false)
{
return ['foo'];
}

protected function extractAttributes(object $object, string $format = null, array $context = []): array
{
return [];
}

protected function getAttributeValue(object $object, string $attribute, string $format = null, array $context = [])
{
return $object->$attribute;
}

protected function setAttributeValue(object $object, string $attribute, $value, string $format = null, array $context = [])
{
}
};

$object = new Dummy();
$object->foo = 'foo';
$object->bar = 'bar';

$this->assertSame(['foo' => 'foo'], $normalizer->normalize($object));
}

/**
Expand Down

0 comments on commit ca16751

Please sign in to comment.