Skip to content

Commit

Permalink
minor: use refresh for detached entities (#778)
Browse files Browse the repository at this point in the history
  • Loading branch information
nikophil authored Jan 4, 2025
1 parent 8353bf0 commit 0d66c02
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 21 deletions.
30 changes: 10 additions & 20 deletions src/Persistence/PersistenceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -186,32 +188,20 @@ 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);
}

$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);
}

/**
Expand Down
9 changes: 8 additions & 1 deletion src/Persistence/PersistentObjectFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

/**
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 0d66c02

Please sign in to comment.