[Serializer] Allow to access to the context and various other infos in callbacks and max depth handler

This commit is contained in:
Kévin Dunglas 2018-04-23 16:28:06 +02:00
parent 9ae116f9e5
commit 0e5f74071a
No known key found for this signature in database
GPG Key ID: 4D04EBEF06AAF3A6
3 changed files with 22 additions and 5 deletions

View File

@ -97,11 +97,11 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
$attributeValue = $this->getAttributeValue($object, $attribute, $format, $context);
if ($maxDepthReached) {
$attributeValue = \call_user_func($this->maxDepthHandler, $attributeValue);
$attributeValue = \call_user_func($this->maxDepthHandler, $attributeValue, $object, $attribute, $format, $context);
}
if (isset($this->callbacks[$attribute])) {
$attributeValue = call_user_func($this->callbacks[$attribute], $attributeValue);
$attributeValue = \call_user_func($this->callbacks[$attribute], $attributeValue, $object, $attribute, $format, $context);
}
if (null !== $attributeValue && !is_scalar($attributeValue)) {

View File

@ -426,6 +426,8 @@ class ObjectNormalizerTest extends TestCase
array(
array(
'bar' => function ($bar) {
$this->assertEquals('baz', $bar);
return 'baz';
},
),
@ -435,8 +437,12 @@ class ObjectNormalizerTest extends TestCase
),
array(
array(
'bar' => function ($bar) {
return;
'bar' => function ($value, $object, $attributeName, $format, $context) {
$this->assertSame('baz', $value);
$this->assertInstanceOf(ObjectConstructorDummy::class, $object);
$this->assertSame('bar', $attributeName);
$this->assertSame('any', $format);
$this->assertArrayHasKey('circular_reference_limit', $context);
},
),
'baz',
@ -634,6 +640,18 @@ class ObjectNormalizerTest extends TestCase
$result = $serializer->normalize($level1, null, array(ObjectNormalizer::ENABLE_MAX_DEPTH => true));
$this->assertEquals($expected, $result);
$this->normalizer->setMaxDepthHandler(function ($object, $parentObject, $attributeName, $format, $context) {
$this->assertSame('level3', $object);
$this->assertInstanceOf(MaxDepthDummy::class, $parentObject);
$this->assertSame('foo', $attributeName);
$this->assertSame('test', $format);
$this->assertArrayHasKey(ObjectNormalizer::ENABLE_MAX_DEPTH, $context);
return 'handler';
});
$serializer->normalize($level1, 'test', array(ObjectNormalizer::ENABLE_MAX_DEPTH => true));
}
/**

View File

@ -276,7 +276,6 @@ class PropertyNormalizerTest extends TestCase
array(
array(
'bar' => function ($bar) {
return;
},
),
'baz',