Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Tree] Add pre-order and level-order traversals #2498

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ a release.

### Added
- Tree: Add `Nested::ALLOWED_NODE_POSITIONS` constant in order to expose the available node positions
- Tree: Add pre-order and level-order traversals (#2498). Add `getNextNode()` and `getNextNodes()` methods to traverse the tree
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be moved to the ## [Unreleased] section

- Support for `doctrine/collections` 2.0
- Support for `doctrine/event-manager` 2.0
- Loggable: Add `LogEntryInterface` interface in order to be implemented by log entry models
Expand Down
5 changes: 5 additions & 0 deletions doc/tree.md
Original file line number Diff line number Diff line change
Expand Up @@ -1249,6 +1249,11 @@ There are repository methods that are available for you in all the strategies:
* childSort: array || keys allowed: field: field to sort on, dir: direction. 'asc' or 'desc'
- *includeNode*: Using "true", this argument allows you to include in the result the node you passed as the first argument. Defaults to "false".
* **setChildrenIndex** / **getChildrenIndex**: These methods allow you to change the default index used to hold the children when you use the **childrenHierarchy** method. Index defaults to "__children".
* **getNextNode** / **getNextNodes**: These methods allow you to get the next nodes when parsing a nested tree. Arguments:
- *root*: Root node use to select (sub-)tree to use.
- *node*: Current node. Use "null" to get the first one. Default to "null".
- *limit* (only for getNextNodes): Maximum nodes to return. Default to "null".
- *traversalStrategy*: Which strategy to use between "pre_order" and "level_order". Default to "NestedTreeRepository::TRAVERSAL_PRE_ORDER".

This list is not complete yet. We're working on including more methods in the common API offered by repositories of all the strategies.
Soon we'll be adding more helpful methods here.
93 changes: 93 additions & 0 deletions src/Tree/Entity/Repository/NestedTreeRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@
*/
class NestedTreeRepository extends AbstractTreeRepository
{
public const TRAVERSAL_PRE_ORDER = 'pre_order';
public const TRAVERSAL_LEVEL_ORDER = 'level_order';

/**
* Allows the following 'virtual' methods:
* - persistAsFirstChild($node)
Expand Down Expand Up @@ -1158,6 +1161,96 @@
return $this->getNodesHierarchyQuery($node, $direct, $options, $includeNode)->getArrayResult();
}

/**
* @param object $root Root node of the parsed tree
* @param object|null $node Current node. If null, first node will be returned
* @param int|null $limit Maximum nodes to return. If null, all nodes will be returned
* @param string $traversalStrategy Strategy to use to traverse tree
*
* @phpstan-assert self::TRAVERSAL_* $traversalStrategy
*
* @throws InvalidArgumentException if input is invalid
*/
public function getNextNodesQueryBuilder($root, $node = null, ?int $limit = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): QueryBuilder
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public function getNextNodesQueryBuilder($root, $node = null, ?int $limit = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): QueryBuilder
public function getNextNodesQueryBuilder(object $root, ?object $node = null, ?int $limit = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): QueryBuilder

Should we make this method private?

{
$meta = $this->getClassMetadata();
$config = $this->listener->getConfiguration($this->_em, $meta->getName());

if (self::TRAVERSAL_PRE_ORDER === $traversalStrategy) {
$qb = $this->childrenQueryBuilder($root, false, $config['left'], 'ASC', true);
if (null !== $node) {
$wrapped = new EntityWrapper($node, $this->_em);
$qb
->andWhere($qb->expr()->gt('node.'.$config['left'], ':lft'))
->setParameter('lft', $wrapped->getPropertyValue($config['left']))
;
}
} elseif (self::TRAVERSAL_LEVEL_ORDER === $traversalStrategy) {
if (!isset($config['level'])) {
throw new \InvalidArgumentException('TreeLevel must be set to use level order traversal.');

Check warning on line 1190 in src/Tree/Entity/Repository/NestedTreeRepository.php

View check run for this annotation

Codecov / codecov/patch

src/Tree/Entity/Repository/NestedTreeRepository.php#L1190

Added line #L1190 was not covered by tests
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why \InvalidArgumentException? $config['level'] isn't provided as an argument in this method.

}
$qb = $this->childrenQueryBuilder($root, false, [$config['level'], $config['left']], ['DESC', 'ASC'], true);
if (null !== $node) {
$wrapped = new EntityWrapper($node, $this->_em);
$qb
->andWhere(
$qb->expr()->orX(
$qb->expr()->andX(
$qb->expr()->gt('node.'.$config['left'], ':lft'),
$qb->expr()->eq('node.'.$config['level'], ':lvl')
),
$qb->expr()->lt('node.'.$config['level'], ':lvl')
)
)
->setParameter('lvl', $wrapped->getPropertyValue($config['level']))
->setParameter('lft', $wrapped->getPropertyValue($config['left']))
;
}
} else {
throw new InvalidArgumentException(\sprintf('Invalid traversal strategy "%s".', $traversalStrategy));

Check warning on line 1210 in src/Tree/Entity/Repository/NestedTreeRepository.php

View check run for this annotation

Codecov / codecov/patch

src/Tree/Entity/Repository/NestedTreeRepository.php#L1210

Added line #L1210 was not covered by tests
}

if (null !== $limit) {
$qb->setMaxResults($limit);
}

return $qb;
}

/**
* @param object $root Root node of the parsed tree
* @param object|null $node Current node. If null, first node will be returned
* @param int|null $limit Maximum nodes to return. If null, all nodes will be returned
* @param self::TRAVERSAL_* $traversalStrategy Strategy to use to traverse tree
*/
public function getNextNodesQuery($root, $node = null, ?int $limit = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): Query
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public function getNextNodesQuery($root, $node = null, ?int $limit = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): Query
public function getNextNodesQuery(object $root, ?object $node = null, ?int $limit = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): Query

{
return $this->getNextNodesQueryBuilder($root, $node, $limit, $traversalStrategy)->getQuery();
}

/**
* @param object $root Root node of the parsed tree
* @param object|null $node Current node. If null, first node will be returned
* @param self::TRAVERSAL_* $traversalStrategy Strategy to use to traverse tree
*/
public function getNextNode($root, $node = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): ?object
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public function getNextNode($root, $node = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): ?object
public function getNextNode(object $root, ?object $node = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): ?object

{
return $this->getNextNodesQuery($root, $node, 1, $traversalStrategy)->getOneOrNullResult();
}

/**
* @param object $root Root node of the parsed tree
* @param object|null $node Current node. If null, first node will be returned
* @param int|null $limit Maximum nodes to return. If null, all nodes will be returned
* @param self::TRAVERSAL_* $traversalStrategy Strategy to use to traverse tree
*
* @return array<object>
*/
public function getNextNodes($root, $node = null, ?int $limit = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): array
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public function getNextNodes($root, $node = null, ?int $limit = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): array
public function getNextNodes(object $root, ?object $node = null, ?int $limit = null, string $traversalStrategy = self::TRAVERSAL_PRE_ORDER): array

{
return $this->getNextNodesQuery($root, $node, $limit, $traversalStrategy)->getArrayResult();
}

protected function validate()
{
return Strategy::NESTED === $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName();
Expand Down
136 changes: 136 additions & 0 deletions tests/Gedmo/Tree/NestedTreeTraversalTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Doctrine Behavioral Extensions package.
* (c) Gediminas Morkevicius <gediminas.morkevicius@gmail.com> http://www.gediminasm.org
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Gedmo\Tests\Tree;

use Doctrine\Common\EventManager;
use Doctrine\ORM\OptimisticLockException;
use Gedmo\Tests\Tool\BaseTestCaseORM;
use Gedmo\Tests\Tree\Fixture\RootCategory;
use Gedmo\Tree\TreeListener;

/**
* These are tests for Tree traversal
*/
final class NestedTreeTraversalTest extends BaseTestCaseORM
{
private const CATEGORY = RootCategory::class;

protected function setUp(): void
{
parent::setUp();

$evm = new EventManager();
$evm->addEventSubscriber(new TreeListener());

$this->getDefaultMockSqliteEntityManager($evm);
$this->populate();
}

/**
* @dataProvider provideNextNodes
*/
public function testNextNode(array $expected, string $strategy): void
{
$repo = $this->em->getRepository(self::CATEGORY);
$lvl1 = $repo->findOneBy(['title' => 'Part. 1']);

$result = [];

$current = null;
while (null !== ($current = $repo->getNextNode($lvl1, $current, $strategy))) {
$result[] = $current->getTitle();
}
static::assertSame($expected, $result);
}

/**
* @dataProvider provideNextNodes
*/
public function testNextNodes(array $expected, string $strategy): void
{
$repo = $this->em->getRepository(self::CATEGORY);
$lvl1 = $repo->findOneBy(['title' => 'Part. 1']);

$nextNodes = $repo->getNextNodes($lvl1, null, 10, $strategy);

static::assertSame($expected, array_column($nextNodes, 'title'));
}

public function provideNextNodes(): iterable
{
yield 'Pre-order traversal' => [
['Part. 1', 'Part. 1.1', 'Part. 1.2', 'Part. 1.2.1', 'Part. 1.2.2', 'Part. 1.3'],
'pre_order',
];
yield 'Level-order traversal' => [
['Part. 1.2.1', 'Part. 1.2.2', 'Part. 1.1', 'Part. 1.2', 'Part. 1.3', 'Part. 1'],
'level_order',
];
}

protected function getUsedEntityFixtures(): array
{
return [self::CATEGORY];
}

/**
* @throws OptimisticLockException
*/
private function populate(): void
{
$lvl1 = new RootCategory();
$lvl1->setTitle('Part. 1');

$lvl2 = new RootCategory();
$lvl2->setTitle('Part. 2');

$lvl11 = new RootCategory();
$lvl11->setTitle('Part. 1.1');
$lvl11->setParent($lvl1);

$lvl12 = new RootCategory();
$lvl12->setTitle('Part. 1.2');
$lvl12->setParent($lvl1);

$lvl121 = new RootCategory();
$lvl121->setTitle('Part. 1.2.1');
$lvl121->setParent($lvl12);

$lvl122 = new RootCategory();
$lvl122->setTitle('Part. 1.2.2');
$lvl122->setParent($lvl12);

$lvl13 = new RootCategory();
$lvl13->setTitle('Part. 1.3');
$lvl13->setParent($lvl1);

$lvl21 = new RootCategory();
$lvl21->setTitle('Part. 2.1');
$lvl21->setParent($lvl2);

$lvl22 = new RootCategory();
$lvl22->setTitle('Part. 2.2');
$lvl22->setParent($lvl2);

$this->em->persist($lvl1);
$this->em->persist($lvl2);
$this->em->persist($lvl11);
$this->em->persist($lvl12);
$this->em->persist($lvl121);
$this->em->persist($lvl122);
$this->em->persist($lvl13);
$this->em->persist($lvl21);
$this->em->persist($lvl22);
$this->em->flush();
$this->em->clear();
}
}