Skip to content

Serializer thrown exception when property have "class-string<>" annotation  #47736

Closed as not planned
@Tygygygydyk

Description

@Tygygygydyk

Symfony version(s) affected

5.4

Description

When a class have a property annotated with class-string<> or string&class-string<> serializer throws an exception:

Uncaught Symfony\Component\Serializer\Exception\NotNormalizableValueException: The type of the "..." attribute for class "..." must be one of "class-string<...>" ("string" given).

How to reproduce

<?php
require_once __DIR__.'/vendor/autoload.php';

use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;

interface SomeInterface {
    public function get(): void;
}
class SomeClass implements SomeInterface {
    public function get(): void {}
}
class FooBar {
    /**
     * @var class-string<SomeInterface>
     */
    private $foo;

    /**
     * @param class-string<SomeInterface> $foo
     */
    public function __construct(string $foo) {
        $this->foo = $foo;
    }

    /**
     * @return class-string<SomeInterface>
     */
    public function getFoo(): string
    {
        return $this->foo;
    }
}

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$serializer = new Serializer([
    new DateTimeNormalizer(),
    new ArrayDenormalizer(),
    new ObjectNormalizer($classMetadataFactory, null, null, new PhpDocExtractor()),
], [new JsonEncoder()]);

$serializer->deserialize('{"foo": "'.SomeClass::class.'"}', FooBar::class, 'json', [AbstractObjectNormalizer::SKIP_NULL_VALUES => true]);

Possible Solution

No response

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions