Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Serializer] Support multiple levels of discriminator mapping #37628

Conversation

jeroennoten
Copy link
Contributor

Q A
Branch? 4.4
Bug fix? yes
New feature? no
Deprecations? no
License MIT

When using multiple levels of discriminator mapping for denormalizing to a multiple level class hierarchy, only the top level discriminator mapping is considered, resulting in an error: Cannot instantiate abstract class ...

Example:

/**
 * @DiscriminatorMap(typeProperty="type", mapping={"group"=GroupNode::class, "item"=ItemNode::class})
 */
abstract class Node {
    // ...
}

class GroupNode extends Node {
    // ...
}

/**
 * @DiscriminatorMap(typeProperty="item_type", mapping={"foo"=FooItemNode::class, "bar"=BarItemNode::class})
 */
abstract class ItemNode extends Node {
    // ...
}

class FooItemNode {
    // ...
}

class BarItemNode {
    // ...
}

$objectNormalizer = new ObjectNormalizer(new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())));
$node = $objectNormalizer->denormalize(['type' => 'item', 'item_type' => 'foo']);

This results in an error: Cannot instantiate abstract class ItemNode. Expected is that $node is of type FooItemNode after denormalization.

The solution is to recursively call AbstractObjectNormalizer::instantiateObject() when a mapping is found, instead of always calling parent::instantiateObject().

@jeroennoten jeroennoten force-pushed the serializer-support-multiple-levels-of-discriminator-mapping branch from fee3842 to b90486c Compare July 21, 2020 15:09
@jeroennoten jeroennoten force-pushed the serializer-support-multiple-levels-of-discriminator-mapping branch from b90486c to 324ad95 Compare July 21, 2020 15:17
@nicolas-grekas nicolas-grekas added this to the 4.4 milestone Jul 22, 2020
@fabpot
Copy link
Member

fabpot commented Jul 23, 2020

Thank you @jeroennoten.

@fabpot fabpot merged commit 2dbbe50 into symfony:4.4 Jul 23, 2020
This was referenced Jul 24, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants