Skip to content

fix(state): object-mapper reuse related entity #7300

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

Merged
merged 1 commit into from
Jul 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@
"symfony/maker-bundle": "^1.24",
"symfony/mercure-bundle": "*",
"symfony/messenger": "^6.4 || ^7.0",
"symfony/object-mapper": "^7.3",
"symfony/object-mapper": "7.4.x-dev",
"symfony/routing": "^6.4 || ^7.0",
"symfony/security-bundle": "^6.4 || ^7.0",
"symfony/security-core": "^6.4 || ^7.0",
Expand Down
25 changes: 25 additions & 0 deletions src/State/ObjectMapper/ClearObjectMapInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\State\ObjectMapper;

/**
* @internal
*/
interface ClearObjectMapInterface
{
/**
* Clear object map to free memory.
*/
public function clearObjectMap(): void;
}
51 changes: 51 additions & 0 deletions src/State/ObjectMapper/ObjectMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\State\ObjectMapper;

use Symfony\Component\ObjectMapper\ObjectMapperAwareInterface;
use Symfony\Component\ObjectMapper\ObjectMapperInterface;

final class ObjectMapper implements ObjectMapperInterface, ClearObjectMapInterface
{
private ?\SplObjectStorage $objectMap = null;

public function __construct(private ObjectMapperInterface $decorated)
{
if (null === $this->objectMap) {
$this->objectMap = new \SplObjectStorage();
}

if ($this->decorated instanceof ObjectMapperAwareInterface) {
$this->decorated = $this->decorated->withObjectMapper($this);
}
}

public function map(object $source, object|string|null $target = null): object
{
if (!\is_object($target) && isset($this->objectMap[$source])) {
$target = $this->objectMap[$source];
}
$mapped = $this->decorated->map($source, $target);
$this->objectMap[$mapped] = $source;
Copy link
Contributor

@mrossard mrossard Jul 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't you also add $this->objectMap[$source] = $target; ? In persist operations you have multiple back and forth mappings between resource and entity.

This probably should be indexed by the object class too, otherwise multiple mappings will not work - you'll get errors similar to what was fixed by #7311

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you have a test case for this?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll try to build one, but you can imagine something like a resource that includes 2 different subresources that are actually representations of the same entity. You'd be storing that $entity maps to $firstResource, then on the call for SecondResource::class you'd get back $firstResource.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

...and if it was about the first part of my comment, ObjectMapperProcessor does the transformation both ways :

  • first the resource is mapped to the entity
  • the entity is persisted
  • the entity is mapped back to the resource

But as i'm writing this i realize it shouldn't reuse the previous object since its contents can change on persist, so you can just ignore my ramblings :D


return $mapped;
}

public function clearObjectMap(): void
{
foreach ($this->objectMap as $k) {
$this->objectMap->detach($k);
}
}
}
9 changes: 8 additions & 1 deletion src/State/Processor/ObjectMapperProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace ApiPlatform\State\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ObjectMapper\ClearObjectMapInterface;
use ApiPlatform\State\ProcessorInterface;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\ObjectMapper\ObjectMapperInterface;
Expand Down Expand Up @@ -42,6 +43,12 @@ public function process(mixed $data, Operation $operation, array $uriVariables =
return $this->decorated->process($data, $operation, $uriVariables, $context);
}

return $this->objectMapper->map($this->decorated->process($this->objectMapper->map($data), $operation, $uriVariables, $context), $operation->getClass());
$data = $this->objectMapper->map($this->decorated->process($this->objectMapper->map($data), $operation, $uriVariables, $context), $operation->getClass());

if ($this->objectMapper instanceof ClearObjectMapInterface) {
$this->objectMapper->clearObjectMap();
}

return $data;
}
}
20 changes: 17 additions & 3 deletions src/Symfony/Bundle/Resources/config/state/object_mapper.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,27 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="api_platform.state_provider.object_mapper" class="ApiPlatform\State\Provider\ObjectMapperProvider" decorates="api_platform.state_provider.read">
<argument type="service" id="object_mapper" on-invalid="null" />
<service id="api_platform.object_mapper.metadata_factory" class="Symfony\Component\ObjectMapper\Metadata\ReflectionObjectMapperMetadataFactory">
</service>

<service id="api_platform.object_mapper" class="Symfony\Component\ObjectMapper\ObjectMapper">
<argument type="service" id="api_platform.object_mapper.metadata_factory" />
<argument type="service" id="property_accessor" on-invalid="null" />
<argument type="tagged_locator" tag="object_mapper.transform_callable"/>
<argument type="tagged_locator" tag="object_mapper.condition_callable"/>
</service>

<service id="api_platform.object_mapper.relation" class="ApiPlatform\State\ObjectMapper\ObjectMapper" decorates="api_platform.object_mapper" decoration-priority="-255">
<argument type="service" id="api_platform.object_mapper.relation.inner" />
</service>

<service id="api_platform.state_provider.object_mapper" class="ApiPlatform\State\Provider\ObjectMapperProvider" decorates="api_platform.state_provider.locator">
<argument type="service" id="api_platform.object_mapper" on-invalid="null" />
<argument type="service" id="api_platform.state_provider.object_mapper.inner" />
</service>

<service id="api_platform.state_processor.object_mapper" class="ApiPlatform\State\Processor\ObjectMapperProcessor" decorates="api_platform.state_processor.locator">
<argument type="service" id="object_mapper" on-invalid="null" />
<argument type="service" id="api_platform.object_mapper" on-invalid="null" />
<argument type="service" id="api_platform.state_processor.object_mapper.inner" />
</service>
</services>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource;

use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\JsonLd\ContextBuilder;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Put;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedResourceWithRelationEntity;
use Symfony\Component\ObjectMapper\Attribute\Map;

#[ApiResource(
stateOptions: new Options(entityClass: MappedResourceWithRelationEntity::class),
normalizationContext: [ContextBuilder::HYDRA_CONTEXT_HAS_PREFIX => false],
extraProperties: [
'standard_put' => true,
],
operations: [
new Get(),
new Put(allowCreate: true),
]
)]
#[Map(target: MappedResourceWithRelationEntity::class)]
class MappedResourceWithRelation
{
public ?string $id = null;
#[Map(if: false)]
public ?string $relationName = null;
#[Map(target: 'related')]
public ?MappedResourceWithRelationRelated $relation = null;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource;

use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\JsonLd\ContextBuilder;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\NotExposed;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedResourceWithRelationRelatedEntity;
use Symfony\Component\ObjectMapper\Attribute\Map;

#[ApiResource(
operations: [
new NotExposed(
stateOptions: new Options(entityClass: MappedResourceWithRelationRelatedEntity::class),
normalizationContext: [ContextBuilder::HYDRA_CONTEXT_HAS_PREFIX => false],
),
],
graphQlOperations: []
)]
#[Map(target: MappedResourceWithRelationRelatedEntity::class)]
class MappedResourceWithRelationRelated
{
#[Map(if: false)]
public string $id;

public string $name;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity;

use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceWithRelation;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\ObjectMapper\Attribute\Map;

#[ORM\Entity]
#[Map(target: MappedResourceWithRelation::class)]
class MappedResourceWithRelationEntity
{
#[ORM\Id, ORM\Column]
private ?int $id = null;

#[ORM\ManyToOne(targetEntity: MappedResourceWithRelationRelatedEntity::class)]
#[Map(target: 'relation')]
#[Map(target: 'relationName', transform: [self::class, 'transformRelation'])]
private ?MappedResourceWithRelationRelatedEntity $related = null;

public static function transformRelation($value, $source)
{
return $source->getRelated()->name;
}

public function getId(): ?int
{
return $this->id;
}

public function setId(?int $id = null)
{
$this->id = $id;

return $this;
}

public function getRelated(): ?MappedResourceWithRelationRelatedEntity
{
return $this->related;
}

public function setRelated(?MappedResourceWithRelationRelatedEntity $related): self
{
$this->related = $related;

return $this;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity;

use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceWithRelationRelated;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\ObjectMapper\Attribute\Map;

#[ORM\Entity]
#[Map(target: MappedResourceWithRelationRelated::class)]
class MappedResourceWithRelationRelatedEntity
{
#[ORM\Id, ORM\Column, ORM\GeneratedValue]
private ?int $id = null;

#[ORM\Column]
public string $name;

public function getId(): ?int
{
return $this->id;
}
}
Loading
Loading