Skip to content

Commit 7269be4

Browse files
authored
Merge pull request #1782 from alanpoulain/fix/persist-only-when-needed
Persist data in Doctrine DataPersister only if needed
2 parents b9d2b17 + cedaa3f commit 7269be4

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/Bridge/Doctrine/Common/DataPersister.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,10 @@ public function persist($data)
5151
return;
5252
}
5353

54-
$manager->persist($data);
54+
if (!$manager->contains($data)) {
55+
$manager->persist($data);
56+
}
57+
5558
$manager->flush();
5659
$manager->refresh($data);
5760
}

tests/Bridge/Doctrine/Common/DataPersisterTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ public function testPersist()
4848
$dummy = new Dummy();
4949

5050
$objectManagerProphecy = $this->prophesize(ObjectManager::class);
51+
$objectManagerProphecy->contains($dummy)->willReturn(false);
5152
$objectManagerProphecy->persist($dummy)->shouldBeCalled();
5253
$objectManagerProphecy->flush()->shouldBeCalled();
5354
$objectManagerProphecy->refresh($dummy)->shouldBeCalled();
@@ -58,6 +59,22 @@ public function testPersist()
5859
(new DataPersister($managerRegistryProphecy->reveal()))->persist($dummy);
5960
}
6061

62+
public function testPersistIfEntityAlreadyManaged()
63+
{
64+
$dummy = new Dummy();
65+
66+
$objectManagerProphecy = $this->prophesize(ObjectManager::class);
67+
$objectManagerProphecy->contains($dummy)->willReturn(true);
68+
$objectManagerProphecy->persist($dummy)->shouldNotBeCalled();
69+
$objectManagerProphecy->flush()->shouldBeCalled();
70+
$objectManagerProphecy->refresh($dummy)->shouldBeCalled();
71+
72+
$managerRegistryProphecy = $this->prophesize(ManagerRegistry::class);
73+
$managerRegistryProphecy->getManagerForClass(Dummy::class)->willReturn($objectManagerProphecy->reveal())->shouldBeCalled();
74+
75+
(new DataPersister($managerRegistryProphecy->reveal()))->persist($dummy);
76+
}
77+
6178
public function testPersistWithNullManager()
6279
{
6380
$managerRegistryProphecy = $this->prophesize(ManagerRegistry::class);

0 commit comments

Comments
 (0)