diff --git a/src/Persistence/PersistenceManager.php b/src/Persistence/PersistenceManager.php index ecee37f1..3525791f 100644 --- a/src/Persistence/PersistenceManager.php +++ b/src/Persistence/PersistenceManager.php @@ -155,8 +155,10 @@ public function refresh(object &$object, bool $force = false): object $strategy = $this->strategyFor($object::class); - if ($strategy->hasChanges($object)) { - throw RefreshObjectFailed::objectHasUnsavedChanges($object::class); + if (!$force) { + if ($strategy->hasChanges($object)) { + throw RefreshObjectFailed::objectHasUnsavedChanges($object::class); + } } $om = $strategy->objectManagerFor($object::class); @@ -186,15 +188,12 @@ public function refresh(object &$object, bool $force = false): object return $object; } - /** - * @template T of object - * - * @param T $object - * - * @return ?T - */ - public function findPersisted(object $object): ?object + public function isPersisted(object $object): bool { + if ($this->strategyFor($object::class)->isScheduledForInsert($object)) { + return false; + } + if ($object instanceof Proxy) { $object = unproxy($object); } @@ -202,16 +201,7 @@ public function findPersisted(object $object): ?object $om = $this->strategyFor($object::class)->objectManagerFor($object::class); $id = $om->getClassMetadata($object::class)->getIdentifierValues($object); - if (!$id) { - return null; - } - - return $om->find($object::class, $id); - } - - public function isPersisted(object $object): bool - { - return !$this->strategyFor($object::class)->isScheduledForInsert($object) && $this->findPersisted($object); + return $id && null !== $om->find($object::class, $id); } /** diff --git a/src/Persistence/PersistentObjectFactory.php b/src/Persistence/PersistentObjectFactory.php index d6a6ec19..d02a03cb 100644 --- a/src/Persistence/PersistentObjectFactory.php +++ b/src/Persistence/PersistentObjectFactory.php @@ -12,6 +12,7 @@ namespace Zenstruck\Foundry\Persistence; use Doctrine\Persistence\ObjectRepository; +use Symfony\Component\VarExporter\Exception\LogicException as VarExportLogicException; use Zenstruck\Foundry\Configuration; use Zenstruck\Foundry\Exception\PersistenceDisabled; use Zenstruck\Foundry\Exception\PersistenceNotAvailable; @@ -20,6 +21,8 @@ use Zenstruck\Foundry\ObjectFactory; use Zenstruck\Foundry\Persistence\Exception\NotEnoughObjects; +use Zenstruck\Foundry\Persistence\Exception\RefreshObjectFailed; + use function Zenstruck\Foundry\set; /** @@ -357,7 +360,11 @@ protected function normalizeObject(object $object): object return $object; } - return $configuration->persistence()->findPersisted($object) ?? $object; + try { + return $configuration->persistence()->refresh($object, true); + } catch (RefreshObjectFailed|VarExportLogicException) { + return $object; + } } final protected function isPersisting(): bool