Skip to content

[ObjectMapper] Cannot map doctrine proxy objects due to reflection not finding map attributes #61050

Open
@tandev

Description

@tandev

Symfony version(s) affected

7.3

Description

the 7.3 ObjectMapper component cannot handle objects like doctrine proxies reliably, specificially the
ObjectMapper::getSourceReflectionClass(object $source, \ReflectionClass $targetRefl): \ReflectionClass will reflect the proxy itself and not the underlying entity and its properties

It will fail with an error like

Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException: Can't get a way to read the property "identifier" in class "Proxies\__CG__\App\Entity\Foo".

(Only checked with < PHP 8.4, its not using the php internal proxy objects)

How to reproduce

I created an Reproducer

https://github.com/tandev/doctrine_proxy_object_mapper_reproducer/blob/main/tests/DoctrineProxyMappingTest.php

 public function test(): void
    {
        $objectMapper = new ObjectMapper(new ReflectionObjectMapperMetadataFactory(),
            new PropertyAccessor(),
        );

        $foo = new Foo();
        $foo->setName('bar');

        $fooDto = $objectMapper->map($foo, FooDto::class);
        self::assertInstanceOf(FooDto::class, $fooDto);

// works

        $this->entityManager->persist($foo);
        $this->entityManager->flush();

        $proxy = $this->entityManager->getProxyFactory()->getProxy(Foo::class, ['id' => 1])->setName('bar');

        $fooDto = $objectMapper->map($proxy, FooDto::class);
        self::assertInstanceOf(FooDto::class, $fooDto);

//fails
    }

fails with

1) App\Tests\DoctrineProxyMappingTest::test
Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException: Can't get a way to read the property "identifier" in class "Proxies\__CG__\App\Entity\Foo".

Possible Solution

Look at parent reflection

like for example some component like PropertyNormalizer does to be able to handle that

https://github.com/symfony/symfony/blob/7.4/src/Symfony/Component/Serializer/Normalizer/PropertyNormalizer.php#L190

The following commit i made might be a possible fix.

I failed to create an appropriate test case due to not understanding how the proxy object hinders reflection

3ef6365

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

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy