Returns descendants nodes as tree with self node in the root.

@param int $depth = null
@return MaterializedPathBehavior|ActiveRecord
543747
public function populateTree($depth = null)
    {
        /** @var ActiveRecord|MaterializedPathBehavior $nodes */
        $nodes = $this
            ->getDescendants($depth)
            ->indexBy($this->keyAttribute)
            ->all();
        $relates = [];
        foreach ($nodes as $key => $node) {
            $parentKey = $node->getParentKey();
            if (!isset($relates[$parentKey])) {
                $relates[$parentKey] = [];
            }
            $relates[$parentKey][] = $node;
        }
        $nodes[$this->owner->{$this->keyAttribute}] = $this->owner;
        foreach ($relates as $key => $children) {
            $nodes[$key]->populateRelation('children', $children);
        }
        return $this->owner;
    }
720288
protected function _pruneTree(int $depth): int
    {
        for ($i = $depth; $i > 0; --$i) {
            foreach ($this->_nodesAtDepth($i) as $node) {
                if (!count($node)) {
                    $node->remove();
                }
            }
        }
        // if root has no children left
        if (!count($this->_root)) {
            $this->_root = null;
            return 0;
        }
        return $this->_root->nodeCount();
    }
314398
public function flatten($depth = INF): CollectionInterface
    {
        return $this->wrap(function (Iterator $data) use ($depth) {
            $lowerDepth = $depth === INF ? INF : $depth - 1;
            foreach ($data as $key => $datum) {
                if ($lowerDepth >= 0 && is_iterable($datum)) {
                    $collection = $this::make($datum);

                    foreach ($collection->flatten($lowerDepth)->getIterator() as $item) {
                        yield $item;
                    }
                } else {
                    yield $datum;
                }
            }
        });
    }
316242
static function traversableToArray($traversable, $depth = 0) {
		$vrat = array();
		if ($depth > 10) throw new \RuntimeException("Recursion is too deep.");
		if (!is_array($traversable) and !($traversable instanceof \Traversable)) {
			throw new \InvalidArgumentException("\$traversable must be an array or Traversable object.");
		}
		foreach ($traversable as $i=>$r) {
			if (is_array($r) or ($r instanceof \Traversable)) {
				$vrat[$i] = self::traversableToArray($r, $depth + 1);
			} else {
				$vrat[$i] = $r;
			}
		}
		return $vrat;
	}
675486
public function toArrayRaw(Entity $entity, $depth=0) {
		$res = [];

		foreach($entity->getDefinition()->properties() as $name=>$property) {
			if($entity->getDefinition()->property($name) instanceof Property\EntityProperty) {
				if($depth < 1)
					$res[$name] = $entity->get($name, null, false);
				else {
					if($entity->getDefinition()->property($name)->get('many')) {
						foreach($entity->get($name, null, false) as $subentity)
							$res[$name][] = $subentity->toArrayRaw($depth-1);
					}
					else {
						if($subentity = $entity->get($name, null, false))
							$res[$name] = $subentity->toArrayRaw($depth-1);
						else
							$res[$name] = null;
					}
				}
			}
			elseif($entity->getDefinition()->property($name)->get('many'))
				$res[$name] = $entity->get($name)->all();
			else
				$res[$name] = $entity->get($name);
		}

		return $res;
	}
590303
public function children($depth = false)
    {
        return $this->menu->whereParentId($this->id, $depth)->all();
    }
1241311
public function build($includeRoot = false, $root = null, $depth = null)
    {
        $root = $root === null ? $this->getRoot() : $root;
        $depth = $depth === null ? $this->depth : $depth;

        $result = [];

        /** @var NodeInterface $childNode */
        foreach ($root->getChildNodes($this->nodeTypeFilter) as $childNode) {
            $hasChildNodes = $childNode->hasChildNodes($this->nodeTypeFilter);
            $shouldLoadChildNodes = $hasChildNodes && ($depth > 1 || $this->isInRootLine($this->active, $childNode));

            $result[$childNode->getName()] = [
                'label' => $childNode->getNodeType()->isOfType('Neos.Neos:Document') ?
                    $childNode->getProperty('title') : $childNode->getLabel(),
                'contextPath' => $childNode->getContextPath(),
                'nodeType' => $childNode->getNodeType()->getName(),
                'hasChildren' => $hasChildNodes,
                'isActive' => $this->active && ($childNode->getPath() === $this->active->getPath()),
                'isFocused' => $this->active && ($childNode->getPath() === $this->active->getPath()),
                'isCollapsed' => !$shouldLoadChildNodes,
                'isCollapsable' => $hasChildNodes
            ];

            if ($shouldLoadChildNodes) {
                $result[$childNode->getName()]['children'] =
                    $this->build(false, $childNode, $depth - 1);
            }

            if ($childNode->getNodeType()->isOfType('Neos.Neos:Document')) {
                $result[$childNode->getName()]['href'] = $this->linkingService->createNodeUri(
                    /* $controllerContext */ $this->controllerContext,
                    /* $node */ $childNode,
                    /* $baseNode */ null,
                    /* $format */ null,
                    /* $absolute */ true,
                    /* $arguments */ [],
                    /* $section */ '',
                    /* $addQueryString */ false,
                    /* $argumentsToBeExcludedFromQueryString */ [],
                    /* $resolveShortcuts */ false
                );
            }
        }

        if ($includeRoot) {
            return [
                $root->getName() => [
                    'label' => $root->getNodeType()->isOfType('Neos.Neos:Document') ?
                        $root->getProperty('title') : $root->getLabel(),
                    'icon' => 'globe',
                    'contextPath' => $root->getContextPath(),
                    'nodeType' => $root->getNodeType()->getName(),
                    'hasChildren' => count($result),
                    'isCollapsed' => false,
                    'isActive' => $this->active && ($root->getPath() === $this->active->getPath()),
                    'isFocused' => $this->active && ($root->getPath() === $this->active->getPath()),
                    'children' => $result
                ]
            ];
        }

        return $result;
    }
886437
public static function getFromHierarchy($hierarchy)
    {
        $sep = self::config()->hierarchy_seperator;
        $items = explode($sep, $hierarchy);

        // loop though each item and get the relevent child
        $top_item = CatalogueCategory::get()
            ->filter("Title", $items[0])
            ->first();
        $next_item = null;

        for ($x = 1; $x < count($items); $x++) {
            if ($top_item) {
                $next_item = $top_item
                    ->Children()
                    ->filter("Title", $items[$x])
                    ->first();

                if ($next_item) {
                    $top_item = $next_item;
                } else {
                    break;
                }
            }
        }

        return $top_item;
    }
1325586
public function getFromPath($path, $depth=0, $withParents=false)
    {

         if(isset($this->fs[$path])){
            return $this->fs[$path];
         }

    }
68418
public function getSubtree($id)
    {
        $primaryKey = $this->mapper->getPrimaryKey($this->getTable());
        $entities = $this->getSubtreeData($id, $primaryKey);
        $children = array();
        foreach ($entities as $entity) {
            $key = $entity->ancestor->id;
            if (!isset($children[$key])) {
                $children[$key] = array();
            }
            $children[$key][] = $entity;
        }

        return $this->getChildNodes($id, $children, $entities, $primaryKey);
    }
68624
function flatten(int $depth = 0) {
        $data = $this->flattenDo($this->data, $depth);
        return (new self($data));
    }
10121
protected function getSubtree($node, $depth = 0)
    {
        // Check if this node is limited due to child count
        $numChildren = $this->getNumChildren($node);
        $limited = $this->isNodeLimited($node, $numChildren);

        // Build root rode
        $expanded = $this->isExpanded($node);
        $opened = $this->isTreeOpened($node);
        $count = ($limited && $numChildren > $this->getMaxChildNodes()) ? 0 : $numChildren;
        $output = [
            'node' => $node,
            'marked' => $this->isMarked($node),
            'expanded' => $expanded,
            'opened' => $opened,
            'depth' => $depth,
            'count' => $count, // Count of DB children
            'limited' => $limited, // Flag whether 'items' has been limited
            'children' => [], // Children to return in this request
        ];

        // Don't iterate children if past limit
        // or not expanded (requires subsequent request to get)
        if ($limited || !$expanded) {
            return $output;
        }

        // Get children
        $children = $this->getChildren($node);
        foreach ($children as $child) {
            // Recurse
            if ($this->isMarked($child)) {
                $output['children'][] = $this->getSubtree($child, $depth + 1);
            }
        }
        return $output;
    }
941358
public function menuNodeHierarchy($depth = 10)
    {
        if ($depth == 0) {
            return $this;
        }

        return $this
            ->prototype('array')
                ->children()
                    ->scalarNode('route')->end()
                    ->arrayNode('routeParameters')
                        ->prototype('variable')
                        ->end()
                    ->end()
                    ->scalarNode('uri')->end()
                    ->scalarNode('label')->end()
                    ->booleanNode('display')->defaultTrue()->end()
                    ->booleanNode('displayChildren')->defaultTrue()->end()
                    ->integerNode('order')->end()
                    ->arrayNode('attributes')
                        ->prototype('variable')
                        ->end()
                    ->end()
                    ->arrayNode('linkAttributes')
                        ->prototype('variable')
                        ->end()
                    ->end()
                    ->arrayNode('childrenAttributes')
                        ->prototype('variable')
                        ->end()
                    ->end()
                    ->arrayNode('labelAttributes')
                        ->prototype('variable')
                        ->end()
                    ->end()
                    ->arrayNode('roles')
                        ->prototype('scalar')
                        ->end()
                    ->end()
                    ->arrayNode('extras')
                        ->prototype('scalar')
                        ->end()
                    ->end()
                    ->menuNode('children')->menuNodeHierarchy($depth - 1)
                ->end()
            ->end();
    }
848067
public function getTree( stdClass $params )
	{
		$this->_checkParams( $params, array( 'site', 'items' ) );
		$this->_setLocale( $params->site );

		$manager = $this->_getManager();

		$result = array();
		$items = ( !is_array( $params->items ) ? array( $params->items ) : $params->items );

		foreach( $items as $entry )
		{
			$entry = ( $entry != 'root' ? $entry : null );
			$item = $manager->getTree( $entry, array(), MW_Tree_Manager_Abstract::LEVEL_LIST );
			$result[] = $this->_createNodeArray( $item );
		}

		return array(
			'items' => ( !is_array( $params->items ) ? reset( $result ) : $result ),
			'success' => true,
		);
	}
311070
public function getDescendants($depth = null, $andSelf = false)
    {
        /** @var \yii\db\ActiveQuery|MaterializedPathQueryTrait $query */
        $query = $this->owner->find();
        return $query->descendantsOf($this->owner, $depth, $andSelf);
    }
488021
public function descendants($level = null)
	{
		$instance = self::blank();
		$instance->where('level', '>', $this->level)
		         ->order('lft', 'asc');

		if (isset($level))
		{
			$instance->where('level', '<=', $this->level + $level);
		}

		return $instance->where('lft', '>', $this->lft)
		                ->where('rgt', '<', $this->rgt)
		                ->applyScopesWhere($this);
	}
318148
private function findInitialWrongDepthGap()
    {
        // get nodes where difference to parents depth > 1
        $qb = $this->accountRepository->createQueryBuilder('c2')
            ->select('count(c2.id) as results')
            ->join('c2.parent', 'c1')
            ->where('(c2.depth - 1) <> c1.depth');
        $depthGapResult = $qb->getQuery()->getSingleScalarResult();

        return $depthGapResult;
    }