bug #31026 [Serializer] Add default object class resolver (jdecool)

This PR was squashed before being merged into the 4.2 branch (closes #31026).

Discussion
----------

[Serializer] Add default object class resolver

| Q             | A
| ------------- | ---
| Branch?       | 4.2
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | -

The commit 1d8b5af3f0 introduce a BC break because before that commit the `extractAttributes` the `$object` can be a string which contain the fully qualified name of an object.

To fix the BC break and preserve the new feature, I suggest to create a default object class resolver if it is not set by the developer.

Commits
-------

dd5b8f16f5 [Serializer] Add default object class resolver
This commit is contained in:
Fabien Potencier 2019-04-10 13:09:12 +02:00
commit 98e0975113
2 changed files with 29 additions and 2 deletions

View File

@ -43,7 +43,10 @@ class ObjectNormalizer extends AbstractObjectNormalizer
parent::__construct($classMetadataFactory, $nameConverter, $propertyTypeExtractor, $classDiscriminatorResolver, $objectClassResolver, $defaultContext);
$this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
$this->objectClassResolver = $objectClassResolver;
$this->objectClassResolver = $objectClassResolver ?? function ($class) {
return \is_object($class) ? \get_class($class) : $class;
};
}
/**
@ -63,7 +66,7 @@ class ObjectNormalizer extends AbstractObjectNormalizer
$attributes = [];
// methods
$class = $this->objectClassResolver ? ($this->objectClassResolver)($object) : \get_class($object);
$class = ($this->objectClassResolver)($object);
$reflClass = new \ReflectionClass($class);
foreach ($reflClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflMethod) {

View File

@ -1043,6 +1043,30 @@ class ObjectNormalizerTest extends TestCase
$this->assertArrayHasKey('foo-Symfony\Component\Serializer\Tests\Normalizer\ObjectDummy-json-bar', $normalizer->normalize(new ObjectDummy(), 'json', ['foo' => 'bar']));
}
public function testDefaultObjectClassResolver()
{
$normalizer = new ObjectNormalizer();
$obj = new ObjectDummy();
$obj->setFoo('foo');
$obj->bar = 'bar';
$obj->setBaz(true);
$obj->setCamelCase('camelcase');
$obj->unwantedProperty = 'notwanted';
$this->assertEquals(
[
'foo' => 'foo',
'bar' => 'bar',
'baz' => true,
'fooBar' => 'foobar',
'camelCase' => 'camelcase',
'object' => null,
],
$normalizer->normalize($obj, 'any')
);
}
public function testObjectClassResolver()
{
$classResolver = function ($object) {