Skip to content

Commit

Permalink
bug #31026 [Serializer] Add default object class resolver (jdecool)
Browse files Browse the repository at this point in the history
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 1d8b5af 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
-------

dd5b8f1 [Serializer] Add default object class resolver
  • Loading branch information
fabpot committed Apr 10, 2019
2 parents de53bd6 + dd5b8f1 commit 98e0975
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
Expand Up @@ -43,7 +43,10 @@ public function __construct(ClassMetadataFactoryInterface $classMetadataFactory
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;
};
}

/**
Expand All @@ -63,7 +66,7 @@ protected function extractAttributes($object, $format = null, array $context = [
$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) {
Expand Down
Expand Up @@ -1043,6 +1043,30 @@ public function denormalize($propertyName, string $class = null, string $format
$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) {
Expand Down

0 comments on commit 98e0975

Please sign in to comment.