Add a helper method to detach all (or some) entities of a given class from entity manager

[MAILPOET-5745]
This commit is contained in:
Jan Jakes
2023-11-28 15:59:27 +01:00
committed by Aschepikov
parent 39aa7ad27d
commit 076ee6d5de
2 changed files with 102 additions and 0 deletions

View File

@@ -126,6 +126,24 @@ abstract class Repository {
$this->entityManager->detach($entity);
}
/**
* @param callable(T): bool|null $filter
*/
public function detachAll(callable $filter = null): void {
$className = $this->getEntityClassName();
$rootClassName = $this->entityManager->getClassMetadata($className)->rootEntityName;
$entities = $this->entityManager->getUnitOfWork()->getIdentityMap()[$rootClassName] ?? [];
foreach ($entities as $entity) {
if (!($entity instanceof $className)) {
continue;
}
if ($filter && !$filter($entity)) {
continue;
}
$this->entityManager->detach($entity);
}
}
/**
* @return class-string<T>
*/