Skip to content
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
31 changes: 31 additions & 0 deletions src/Doctrine/Common/State/PersistProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Util\ClassInfoTrait;
use ApiPlatform\State\ProcessorInterface;
use Doctrine\ODM\MongoDB\UnitOfWork as OdmUnitOfWork;
use Doctrine\ORM\UnitOfWork as OrmUnitOfWork;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\ObjectManager as DoctrineObjectManager;

Expand Down Expand Up @@ -221,9 +223,38 @@ private function handleLazyObjectRelations(object $data, DoctrineObjectManager $
continue;
}

// Do not get reference for new objects with application-assigned identifiers (e.g. UUID generated in the constructor):
// the object does not exist in the database yet and must be handled by cascade persist
if ($this->isNewObject($relManager, $value)) {
continue;
}

\assert(method_exists($relManager, 'getReference'));

$reflectionProperty->setValue($data, $relManager->getReference($relClass, $identifiers));
}
}

/**
* Checks if an object holding identifiers is new (not yet in the database) according to the unit of work.
* Objects with database-generated identifiers are never considered new here since Doctrine assumes they exist.
*/
private function isNewObject(DoctrineObjectManager $manager, object $object): bool
{
if (!method_exists($manager, 'getUnitOfWork')) {
return false;
}

$unitOfWork = $manager->getUnitOfWork();

if (method_exists($unitOfWork, 'getEntityState')) {
return OrmUnitOfWork::STATE_NEW === $unitOfWork->getEntityState($object);
}

if (method_exists($unitOfWork, 'getDocumentState')) {
return OdmUnitOfWork::STATE_NEW === $unitOfWork->getDocumentState($object);
}

return false;
}
}
131 changes: 131 additions & 0 deletions src/Doctrine/Common/Tests/State/PersistProcessorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,13 @@
use ApiPlatform\Metadata\Put;
use ApiPlatform\State\ProcessorInterface;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ODM\MongoDB\UnitOfWork as ODMUnitOfWork;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata as ORMClassMetadata;
use Doctrine\ORM\UnitOfWork as ORMUnitOfWork;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\Mapping\ClassMetadata as PersistenceClassMetadata;
use Doctrine\Persistence\Mapping\RuntimeReflectionService;
use Doctrine\Persistence\ObjectManager;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -145,6 +149,60 @@ public function testHandleLazyObjectRelationsSkipsUninitializedProperties(): voi
$this->assertSame($dummy, $result);
}

public function testHandleLazyObjectRelationsKeepsNewOrmRelationWithAssignedIdentifier(): void
{
$relation = new PersistProcessorTestRelationStub();
$data = new PersistProcessorTestObjectWithRelationStub($relation);

$unitOfWork = $this->createMock(ORMUnitOfWork::class);
$unitOfWork->expects($this->once())->method('getEntityState')->with($relation)->willReturn(ORMUnitOfWork::STATE_NEW);

$relationManager = $this->createMock(EntityManagerInterface::class);
$relationManager->method('contains')->with($relation)->willReturn(false);
$relationManager->method('getClassMetadata')->with(PersistProcessorTestRelationStub::class)->willReturn($this->createOrmRelationMetadata());
$relationManager->method('getUnitOfWork')->willReturn($unitOfWork);
$relationManager->expects($this->never())->method('getReference');

$this->processObjectWithRelation($data, $relationManager);

$this->assertSame($relation, $data->relation);
}

public function testHandleLazyObjectRelationsKeepsNewOdmRelationWithAssignedIdentifier(): void
{
$relation = new PersistProcessorTestRelationStub();
$data = new PersistProcessorTestObjectWithRelationStub($relation);

$unitOfWork = $this->createMock(PersistProcessorTestDocumentUnitOfWorkStub::class);
$unitOfWork->expects($this->once())->method('getDocumentState')->with($relation)->willReturn(ODMUnitOfWork::STATE_NEW);

$relationManager = $this->createMockForIntersectionOfInterfaces([ObjectManager::class, PersistProcessorTestDocumentManagerStub::class]);
$relationManager->method('contains')->with($relation)->willReturn(false);
$relationManager->method('getClassMetadata')->with(PersistProcessorTestRelationStub::class)->willReturn($this->createRelationMetadata());
$relationManager->method('getUnitOfWork')->willReturn($unitOfWork);
$relationManager->expects($this->never())->method('getReference');

$this->processObjectWithRelation($data, $relationManager);

$this->assertSame($relation, $data->relation);
}

public function testHandleLazyObjectRelationsReplacesRelationWhenManagerHasNoUnitOfWork(): void
{
$relation = new PersistProcessorTestRelationStub();
$reference = new PersistProcessorTestRelationStub();
$data = new PersistProcessorTestObjectWithRelationStub($relation);

$relationManager = $this->createMockForIntersectionOfInterfaces([ObjectManager::class, PersistProcessorTestReferenceManagerStub::class]);
$relationManager->method('contains')->with($relation)->willReturn(false);
$relationManager->method('getClassMetadata')->with(PersistProcessorTestRelationStub::class)->willReturn($this->createRelationMetadata());
$relationManager->expects($this->once())->method('getReference')->with(PersistProcessorTestRelationStub::class, ['id' => 'relation-id'])->willReturn($reference);

$this->processObjectWithRelation($data, $relationManager);

$this->assertSame($reference, $data->relation);
}

public function testPersistPutCreateResolvesParentLinkViaToProperty(): void
{
$device = new PersistProcessorTestDeviceStub();
Expand Down Expand Up @@ -191,6 +249,41 @@ public function testPersistPutCreateResolvesParentLinkViaToProperty(): void
$this->assertSame($userReference, $device->user);
$this->assertSame('device-uuid', $device->id);
}

private function createRelationMetadata(): PersistenceClassMetadata
{
$metadata = $this->createStub(PersistenceClassMetadata::class);
$metadata->method('getIdentifierValues')->willReturn(['id' => 'relation-id']);

return $metadata;
}

private function createOrmRelationMetadata(): ORMClassMetadata
{
$metadata = new ORMClassMetadata(PersistProcessorTestRelationStub::class);
$metadata->mapField(['fieldName' => 'id', 'type' => 'string', 'id' => true]);
$metadata->wakeupReflection(new RuntimeReflectionService());

return $metadata;
}

private function processObjectWithRelation(PersistProcessorTestObjectWithRelationStub $data, ObjectManager $relationManager): void
{
$dataManager = $this->createMock(ObjectManager::class);
$dataManager->method('getClassMetadata')->with(PersistProcessorTestObjectWithRelationStub::class)->willReturn($this->createStub(PersistenceClassMetadata::class));
$dataManager->method('contains')->with($data)->willReturn(false);
$dataManager->expects($this->once())->method('persist')->with($data);
$dataManager->expects($this->once())->method('flush');
$dataManager->expects($this->once())->method('refresh')->with($data);

$managerRegistry = $this->createStub(ManagerRegistry::class);
$managerRegistry->method('getManagerForClass')->willReturnMap([
[PersistProcessorTestObjectWithRelationStub::class, $dataManager],
[PersistProcessorTestRelationStub::class, $relationManager],
]);

(new PersistProcessor($managerRegistry))->process($data, new Post(map: true));
}
}

/** @internal */
Expand All @@ -205,3 +298,41 @@ class PersistProcessorTestDeviceStub
public ?string $id = null;
public ?PersistProcessorTestUserStub $user = null;
}

/** @internal */
class PersistProcessorTestObjectWithRelationStub
{
public ?string $id = null;

public function __construct(public PersistProcessorTestRelationStub $relation)
{
}
}

/** @internal */
class PersistProcessorTestRelationStub
{
public string $id = 'relation-id';
}

/** @internal */
interface PersistProcessorTestReferenceManagerStub
{
/**
* @param class-string $className
* @param array<string, mixed> $identifier
*/
public function getReference(string $className, array $identifier): object;
}

/** @internal */
interface PersistProcessorTestDocumentManagerStub extends PersistProcessorTestReferenceManagerStub
{
public function getUnitOfWork(): PersistProcessorTestDocumentUnitOfWorkStub;
}

/** @internal */
interface PersistProcessorTestDocumentUnitOfWorkStub
{
public function getDocumentState(object $object): int;
}
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 <dunglas@gmail.com>
*
* 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\Issue8438;

use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Issue8438\Issue8438TaskRuleCondition;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\Uid\Uuid;

#[ApiResource(
operations: [
new Get(),
new Post(),
],
shortName: 'Issue8438TaskRuleCondition',
stateOptions: new Options(entityClass: Issue8438TaskRuleCondition::class)
)]
#[Map(target: Issue8438TaskRuleCondition::class)]
class Issue8438TaskRuleConditionDto
{
public Uuid $id;
public string $completeWhen = '';

public function __construct()
{
// Application-assigned identifier, generated before the entity is persisted
$this->id = Uuid::v7();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* 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\Issue8438;

use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Issue8438\Issue8438TaskRule;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\Uid\Uuid;

#[ApiResource(
operations: [
new Get(),
new Post(),
],
shortName: 'Issue8438TaskRule',
stateOptions: new Options(entityClass: Issue8438TaskRule::class)
)]
#[Map(target: Issue8438TaskRule::class)]
class Issue8438TaskRuleDto
{
public Uuid $id;
public string $name = '';

#[ApiProperty(readableLink: true, writableLink: true)]
public ?Issue8438TaskRuleConditionDto $condition = null;

public function __construct()
{
// Application-assigned identifier, generated before the entity is persisted
$this->id = Uuid::v7();
}
}
42 changes: 42 additions & 0 deletions tests/Fixtures/TestBundle/Entity/Issue8438/Issue8438TaskRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* 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\Issue8438;

use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Issue8438\Issue8438TaskRuleDto;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\Uid\Uuid;

/**
* Owning side with an application-assigned identifier and cascade persist on the relation.
*/
#[ORM\Entity]
#[Map(target: Issue8438TaskRuleDto::class)]
class Issue8438TaskRule
{
#[ORM\Id]
#[ORM\Column(type: 'symfony_uuid', unique: true)]
public Uuid $id;

public function __construct(
#[ORM\Column(type: 'string', length: 255)]
public string $name = '',
#[ORM\ManyToOne(targetEntity: Issue8438TaskRuleCondition::class, cascade: ['persist'])]
#[ORM\JoinColumn(nullable: true)]
public ?Issue8438TaskRuleCondition $condition = null,
?Uuid $id = null,
) {
$this->id = $id ?? Uuid::v7();
}
}
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 <dunglas@gmail.com>
*
* 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\Issue8438;

use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Issue8438\Issue8438TaskRuleConditionDto;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\Uid\Uuid;

/**
* Related entity with an application-assigned identifier (no DB-generated id).
*/
#[ORM\Entity]
#[Map(target: Issue8438TaskRuleConditionDto::class)]
class Issue8438TaskRuleCondition
{
#[ORM\Id]
#[ORM\Column(type: 'symfony_uuid', unique: true)]
public Uuid $id;

public function __construct(
#[ORM\Column(type: 'string', length: 255)]
public string $completeWhen = '',
?Uuid $id = null,
) {
$this->id = $id ?? Uuid::v7();
}
}
Loading
Loading