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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
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) {

Check failure on line 29 in src/State/ObjectMapper/ObjectMapper.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Class Symfony\Component\ObjectMapper\ObjectMapperAwareInterface not found.
$this->decorated = $this->decorated->withObjectMapper($this);

Check failure on line 30 in src/State/ObjectMapper/ObjectMapper.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Call to method withObjectMapper() on an unknown class Symfony\Component\ObjectMapper\ObjectMapperAwareInterface.
}
}

public function map(object $source, object|string|null $target = null): object
{
if (isset($this->objectMap[$source])) {
Copy link
Member

Choose a reason for hiding this comment

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

Don't we want to check if a target has not been given explicitly by the user before overriding it?

$target = $this->objectMap[$source];
}
$mapped = $this->decorated->map($source, $target);
$this->objectMap[$mapped] = $source;

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));
$data = $this->objectMapper->map($this->decorated->process($this->objectMapper->map($data), $operation, $uriVariables, $context));

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

return $data;
}
}
17 changes: 14 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,24 @@
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" class="Symfony\Component\ObjectMapper\ObjectMapper">
<argument type="service" id="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,33 @@
<?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\NotExposed;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedResourceWithRelationRelatedEntity;
use Symfony\Component\ObjectMapper\Attribute\Map;

#[NotExposed(
stateOptions: new Options(entityClass: MappedResourceWithRelationRelatedEntity::class),
normalizationContext: [ContextBuilder::HYDRA_CONTEXT_HAS_PREFIX => false],
)]
#[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;
}
}
46 changes: 44 additions & 2 deletions tests/Functional/MappingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResource;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceOdm;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceWithRelation;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceWithRelationRelated;
use ApiPlatform\Tests\Fixtures\TestBundle\Document\MappedDocument;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedEntity;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedResourceWithRelationEntity;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedResourceWithRelationRelatedEntity;
use ApiPlatform\Tests\RecreateSchemaTrait;
use ApiPlatform\Tests\SetupClassResourcesTrait;
use Doctrine\ODM\MongoDB\DocumentManager;
Expand All @@ -33,12 +37,12 @@ final class MappingTest extends ApiTestCase
*/
public static function getResources(): array
{
return [MappedResource::class, MappedResourceOdm::class];
return [MappedResource::class, MappedResourceOdm::class, MappedResourceWithRelation::class, MappedResourceWithRelationRelated::class];
}

public function testShouldMapBetweenResourceAndEntity(): void
{
if (!$this->getContainer()->has('object_mapper')) {
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}

Expand Down Expand Up @@ -68,6 +72,44 @@ public function testShouldMapBetweenResourceAndEntity(): void
$this->assertJsonContains(['username' => 'ba zar']);
}

public function testMapPutAllowCreate(): void
{
if (!$this->getContainer()->has('api_platform.object_mapper')) {
$this->markTestSkipped('ObjectMapper not installed');
}

if ($this->isMongoDB()) {
$this->markTestSkipped('MongoDB is not tested');
}

$this->recreateSchema([MappedResourceWithRelationEntity::class, MappedResourceWithRelationRelatedEntity::class]);
$manager = $this->getManager();

$e = new MappedResourceWithRelationRelatedEntity();
$e->name = 'test';
$manager->persist($e);
$manager->flush();

self::createClient()->request('PUT', '/mapped_resource_with_relations/4', [
'json' => [
'@id' => '/mapped_resource_with_relations/4',
'relation' => '/mapped_resource_with_relation_relateds/'.$e->getId(),
],
'headers' => [
'content-type' => 'application/ld+json',
],
]);

$this->assertJsonContains([
'@context' => '/contexts/MappedResourceWithRelation',
'@id' => '/mapped_resource_with_relations/4',
'@type' => 'MappedResourceWithRelation',
'id' => '4',
'relationName' => 'test',
'relation' => '/mapped_resource_with_relation_relateds/1',
]);
}

private function loadFixtures(): void
{
$manager = $this->getManager();
Expand Down
Loading