Skip to content

Commit

Permalink
Use iterators instead of arrays for query results where possible
Browse files Browse the repository at this point in the history
  • Loading branch information
phansys authored and franmomu committed Sep 7, 2023
1 parent 25c63bb commit 4010c0c
Show file tree
Hide file tree
Showing 10 changed files with 50 additions and 48 deletions.
25 changes: 15 additions & 10 deletions src/Loggable/Entity/Repository/LogEntryRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,7 @@ class LogEntryRepository extends EntityRepository
*/
public function getLogEntries($entity)
{
$q = $this->getLogEntriesQuery($entity);

return $q->getResult();
return $this->getLogEntriesQuery($entity)->getResult();
}

/**
Expand Down Expand Up @@ -112,7 +110,7 @@ public function revert($entity, $version = 1)
$dql .= ' WHERE log.objectId = :objectId';
$dql .= ' AND log.objectClass = :objectClass';
$dql .= ' AND log.version <= :version';
$dql .= ' ORDER BY log.version ASC';
$dql .= ' ORDER BY log.version DESC';

$objectId = (string) $wrapped->getIdentifier(false, true);
$q = $this->_em->createQuery($dql);
Expand All @@ -121,16 +119,18 @@ public function revert($entity, $version = 1)
'objectClass' => $objectClass,
'version' => $version,
]);
$logs = $q->getResult();

if ([] === $logs) {
throw new UnexpectedValueException('Could not find any log entries under version: '.$version);
}

$config = $this->getLoggableListener()->getConfiguration($this->_em, $objectMeta->getName());
$fields = $config['versioned'];
$filled = false;
while (($log = array_pop($logs)) && !$filled) {
$logsFound = false;

$logs = $q->toIterable();
assert($logs instanceof \Generator);

while ((null !== $log = $logs->current()) && !$filled) {
$logsFound = true;
$logs->next();
if ($data = $log->getData()) {
foreach ($data as $field => $value) {
if (in_array($field, $fields, true)) {
Expand All @@ -142,6 +142,11 @@ public function revert($entity, $version = 1)
}
$filled = [] === $fields;
}

if (!$logsFound) {
throw new UnexpectedValueException('Could not find any log entries under version: '.$version);
}

/*if (count($fields)) {
throw new \Gedmo\Exception\UnexpectedValueException('Could not fully revert the entity to version: '.$version);
}*/
Expand Down
4 changes: 2 additions & 2 deletions src/Sortable/Mapping/Event/Adapter/ORM.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ public function getMaxPosition(array $config, $meta, $groups)
$query = $qb->getQuery();
$query->useQueryCache(false);
$query->disableResultCache();
$res = $query->getResult();
$query->setMaxResults(1);

return $res[0][1];
return $query->getSingleScalarResult();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,9 @@ public function findObjectByTranslatedField($field, $value, $class)
->getQuery();

$q->setHydrate(false);
$result = $q->getIterator()->toArray();
$result = $q->getSingleResult();

$id = $result[0]['foreign_key'] ?? null;
$id = $result['foreign_key'] ?? null;

if (null === $id) {
return null;
Expand Down
8 changes: 3 additions & 5 deletions src/Translatable/Entity/Repository/TranslationRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,8 @@ public function findTranslations($entity)
'entityId' => $entityId,
'entityClass' => $entityClass,
]);
$q = $qb->getQuery();

foreach ($q->getArrayResult() as $row) {
foreach ($qb->getQuery()->toIterable([], Query::HYDRATE_ARRAY) as $row) {
$result[$row['locale']][$row['field']] = $row['content'];
}
}
Expand Down Expand Up @@ -191,8 +190,7 @@ public function findObjectByTranslatedField($field, $value, $class)
'value' => $value,
]);
$q->setMaxResults(1);
$result = $q->getArrayResult();
$id = $result[0]['foreignKey'] ?? null;
$id = $q->getSingleScalarResult();

if (null !== $id) {
$entity = $this->_em->find($class, $id);
Expand Down Expand Up @@ -223,7 +221,7 @@ public function findTranslationsByObjectId($id)
->setParameter('entityId', $id);
$q = $qb->getQuery();

foreach ($q->getArrayResult() as $row) {
foreach ($q->toIterable([], Query::HYDRATE_ARRAY) as $row) {
$result[$row['locale']][$row['field']] = $row['content'];
}
}
Expand Down
7 changes: 1 addition & 6 deletions src/Translatable/Mapping/Event/Adapter/ORM.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,8 @@ public function findTranslation(AbstractWrapper $wrapped, $locale, $field, $tran
}
$q = $qb->getQuery();
$q->setMaxResults(1);
$result = $q->getResult();

if ($result) {
return array_shift($result);
}

return null;
return $q->getOneOrNullResult();
}

public function removeAssociatedTranslations(AbstractWrapper $wrapped, $transClass, $objectClass)
Expand Down
2 changes: 1 addition & 1 deletion src/Tree/Entity/Repository/ClosureTreeRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ public function removeFromTree($node)
$dql .= " WHERE node.{$config['parent']} = :node";
$q = $this->_em->createQuery($dql);
$q->setParameter('node', $node);
$nodesToReparent = $q->getResult();
$nodesToReparent = $q->toIterable();
// process updates in transaction
$this->_em->getConnection()->beginTransaction();

Expand Down
2 changes: 1 addition & 1 deletion src/Tree/Entity/Repository/MaterializedPathRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ public function getNodesHierarchy($node = null, $direct = false, array $options
$nodes = $this->getNodesHierarchyQuery($node, $direct, $options, $includeNode)->getArrayResult();
usort(
$nodes,
static function ($a, $b) use ($path) {
static function (array $a, array $b) use ($path): int {
return strcmp($a[$path], $b[$path]);
}
);
Expand Down
25 changes: 13 additions & 12 deletions src/Tree/Entity/Repository/NestedTreeRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -409,9 +409,7 @@ public function childrenQuery($node = null, $direct = false, $sortByField = null
*/
public function children($node = null, $direct = false, $sortByField = null, $direction = 'ASC', $includeNode = false)
{
$q = $this->childrenQuery($node, $direct, $sortByField, $direction, $includeNode);

return $q->getResult();
return $this->childrenQuery($node, $direct, $sortByField, $direction, $includeNode)->getResult();
}

public function getChildrenQueryBuilder($node = null, $direct = false, $sortByField = null, $direction = 'ASC', $includeNode = false)
Expand Down Expand Up @@ -802,7 +800,7 @@ public function removeFromTree($node)

$qb->andWhere($qb->expr()->eq('node.'.$config['parent'], ':pid'));
$qb->setParameter('pid', $nodeId);
$nodes = $qb->getQuery()->getArrayResult();
$nodes = $qb->getQuery()->toIterable([], Query::HYDRATE_ARRAY);

// go through each of the node's children
foreach ($nodes as $newRoot) {
Expand Down Expand Up @@ -1235,13 +1233,17 @@ private function verifyTree(array &$errors, ?object $root = null): void
$qb->andWhere($qb->expr()->eq('node.'.$config['root'], ':rid'));
$qb->setParameter('rid', $rootId);
}
$nodes = $qb->getQuery()->getArrayResult();
if ([] !== $nodes) {
foreach ($nodes as $node) {
$errors[] = "node [{$node[$identifier]}] has missing parent".($root ? ' on tree root: '.$rootId : '');
}

return; // loading broken relation can cause infinite loop
$areMissingParents = false;

foreach ($qb->getQuery()->toIterable([], Query::HYDRATE_ARRAY) as $node) {
$areMissingParents = true;
$errors[] = "node [{$node[$identifier]}] has missing parent".($root ? ' on tree root: '.$rootId : '');
}

// loading broken relation can cause infinite loop
if ($areMissingParents) {
return;
}

// check for nodes that have a right value lower than the left
Expand Down Expand Up @@ -1272,9 +1274,8 @@ private function verifyTree(array &$errors, ?object $root = null): void
$qb->andWhere($qb->expr()->eq('node.'.$config['root'], ':rid'));
$qb->setParameter('rid', $rootId);
}
$nodes = $qb->getQuery()->getResult(Query::HYDRATE_OBJECT);

foreach ($nodes as $node) {
foreach ($qb->getQuery()->toIterable() as $node) {
$right = $meta->getReflectionProperty($config['right'])->getValue($node);
$left = $meta->getReflectionProperty($config['left'])->getValue($node);
$id = $meta->getReflectionProperty($identifier)->getValue($node);
Expand Down
18 changes: 11 additions & 7 deletions src/Tree/Strategy/ORM/Closure.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata as ORMClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Query;
use Doctrine\Persistence\Mapping\AbstractClassMetadataFactory;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\ObjectManager;
Expand Down Expand Up @@ -302,23 +303,26 @@ public function processPostPersist($em, $entity, AdapterInterface $ea)
$dql .= ' WHERE c.descendant = :parent';
$q = $em->createQuery($dql);
$q->setParameter('parent', $parent);
$ancestors = $q->getArrayResult();

if ([] === $ancestors) {
// The parent has been persisted after the child, postpone the evaluation
$this->pendingChildNodeInserts[$emHash][] = $node;
$mustPostpone = true;

continue;
}
foreach ($q->toIterable([], Query::HYDRATE_ARRAY) as $ancestor) {
$mustPostpone = false;

foreach ($ancestors as $ancestor) {
$entries[] = [
$ancestorColumnName => $ancestor['ancestor'][$identifier],
$descendantColumnName => $nodeId,
$depthColumnName => $ancestor['depth'] + 1,
];
}

if ($mustPostpone) {
// The parent has been persisted after the child, postpone the evaluation
$this->pendingChildNodeInserts[$emHash][] = $node;

continue;
}

if (isset($config['level'])) {
$this->pendingNodesLevelProcess[$nodeId] = $node;
}
Expand Down
3 changes: 1 addition & 2 deletions src/Tree/Strategy/ORM/Nested.php
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,7 @@ public function processScheduledDelete($em, $node)
}
$q = $qb->getQuery();
// get nodes for deletion
$nodes = $q->getResult();
foreach ((array) $nodes as $removalNode) {
foreach ($q->toIterable() as $removalNode) {
$uow->scheduleForDelete($removalNode);
}
}
Expand Down

0 comments on commit 4010c0c

Please sign in to comment.