From e8055f048acc64690e076634a14ca9bf469e27de Mon Sep 17 00:00:00 2001 From: Matthias Pigulla Date: Mon, 5 Jun 2023 22:17:06 +0000 Subject: [PATCH] Avoid unnecessary changes --- lib/Doctrine/ORM/UnitOfWork.php | 19 +++++++++++++++++++ .../ManyToManyBasicAssociationTest.php | 6 +++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/Doctrine/ORM/UnitOfWork.php b/lib/Doctrine/ORM/UnitOfWork.php index 5982947b247..ebb5f12a01b 100644 --- a/lib/Doctrine/ORM/UnitOfWork.php +++ b/lib/Doctrine/ORM/UnitOfWork.php @@ -24,6 +24,7 @@ use Doctrine\ORM\Event\PreRemoveEventArgs; use Doctrine\ORM\Event\PreUpdateEventArgs; use Doctrine\ORM\Exception\ORMException; +use Doctrine\ORM\Exception\UnexpectedAssociationValue; use Doctrine\ORM\Id\AssignedGenerator; use Doctrine\ORM\Internal\CommitOrderCalculator; use Doctrine\ORM\Internal\HydrationCompleteHandler; @@ -955,6 +956,15 @@ private function computeAssociationChanges(array $assoc, $value): void $state = $this->getEntityState($entry, self::STATE_NEW); + if (! ($entry instanceof $assoc['targetEntity'])) { + throw UnexpectedAssociationValue::create( + $assoc['sourceEntity'], + $assoc['fieldName'], + get_debug_type($entry), + $assoc['targetEntity'] + ); + } + switch ($state) { case self::STATE_NEW: if (! $assoc['isCascadePersist']) { @@ -990,6 +1000,15 @@ private function computeAssociationChanges(array $assoc, $value): void $this->pendingCollectionElementRemovals[$coid][$key] = true; break; + + case self::STATE_DETACHED: + // Can actually not happen right now as we assume STATE_NEW, + // so the exception will be raised from the DBAL layer (constraint violation). + throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($assoc, $entry); + + default: + // MANAGED associated entities are already taken into account + // during changeset calculation anyway, since they are in the identity map. } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php index 1284f89ef26..994d2bb8aa5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php @@ -243,10 +243,10 @@ public function testRemoveGroupWithUser(): void { $user = $this->addCmsUserGblancoWithGroups(5); - $anotherUser = new CmsUser(); + $anotherUser = new CmsUser(); $anotherUser->username = 'joe_doe'; - $anotherUser->name = 'Joe Doe'; - $anotherUser->status = 'QA Engineer'; + $anotherUser->name = 'Joe Doe'; + $anotherUser->status = 'QA Engineer'; foreach ($user->getGroups() as $group) { $anotherUser->addGroup($group);