@param array    $flatTree
@param string   $levelName
@param int|null $level
@param int      $startPos
@param array    $result

@return array
421355
private static function _flatToNested(
        array $flatTree,
        string $levelName = 'level',
        ?int $level = null,
        int $startPos = 0,
        array &$result = array()
    ): array {
        $total = count($flatTree);
        $first = true;

        for ($pos = $startPos; $pos < $total; ++$pos) {
            $item = $flatTree[$pos];

            if (null === $level) {
                $level = $item[$levelName];
            }

            if (!array_key_exists('_children', $item)) {
                $item['_children'] = array();
            }

            if ($level == $item[$levelName]) {
                $result[] = $item;
                $first = true;
            } elseif (($level + 1) == $item[$levelName] && true == $first) {
                $children = array($item);
                self::_flatToNested($flatTree, $levelName, (int) $item[$levelName], $pos + 1, $children);
                $result[count($result) - 1]['_children'] = $children;
                $first = false;
            } elseif ($level > $item[$levelName]) {
                break;
            }
        }

        return $result;
    }
988464
private function parseSetResultNodes(DOMElement $child, $name, array &$result = null)
    {
        if (!(is_array($result[$name]) && $this->valueIsList($result[$name]))) {
            return false;
        }

        $value = static::getPhpValue($child, null, $this);

        if (is_array($value) && $this->valueIsList($value)) {
            return $result[$name] = array_merge($result[$name], $value);
        }

        return $result[$name][] = $value;
    }
799640
protected function prepareTree($results)
	{
		$hasRoot = false;
		$map = array();

        // prepares array $path => $localization
		foreach ($results as $localization) {
			/* @var $localization \Supra\Package\Cms\Entity\PageLocalization */

			$path = $localization->getPathEntity();

			if (empty($path)) {
				continue;
			}

			$isActive = $path->isActive() && $localization->isActive();

			if ($isActive) {
				$map[$localization->getFullPath(Path::FORMAT_NO_DELIMITERS)] = $localization;
			}
		}

		// grouping pages by path. Building array tree
		$output = array(
			'children' => array(),
		);

		foreach ($map as $path => $localization) {

			$path = trim($path, '/');

			if (empty($path)) {
				$hasRoot = true;
			}

			$pathParts = explode('/', $path);

			if ($hasRoot && ! empty($path)) {
				array_unshift($pathParts, '');
			}

			$outputReference = &$output;

			while ( ! empty($pathParts)) {

				$part = $pathParts[0];

				if (isset($outputReference['children'][$part])) {
					$outputReference = &$outputReference['children'][$part];
					array_shift($pathParts);
				} else {
					break;
				}
			}

			if (empty($pathParts)) {
				throw new \LogicException("Duplicate element under path $path");
			}
			
			$pathRemainder = implode('/', $pathParts);

			$outputReference['children'][$pathRemainder] = array(
				'localization' => $localization,
				'children' => array(),
			);
		}

		return $output['children'];
	}
380280
public function run(int $totalRecords = null, string $startKey = null, string $stopKey = null): array
    {
        if ($totalRecords !== null) {
            $this->totalRecords = abs($totalRecords);
        }

        if ($startKey) $this->startKey = $startKey;
        if ($stopKey) $this->stopKey = $stopKey;

        // get params could be manipulated by developer setting autorun false
        if ($this->autorun) {
            $this->start = abs($_GET[$this->startKey] ?? 0);
            $this->stop = abs($_GET[$this->stopKey] ?? 0);
        }

        $stop = ($this->stop > 0) ? $this->stop : $this->stopDefault;
        $start = ($this->start > 1) ? ($this->start * $stop) - $stop : 0;

        $this->stop = $stop;
        $this->start = $start;
        if ($this->totalRecords > 0) {
            $this->totalPages = abs((int) ceil($this->totalRecords / $this->stop));
        }

        // safety..
        if (isset($_GET[$this->startKey])) {
            $start = $_GET[$this->startKey];
            if ($start && $start[0] == '-') {
                $this->redirect($this->prepareQuery() . $this->startKey .'='. abs($start), 301);
            } elseif ($start > $this->totalPages) {
                $this->redirect($this->prepareQuery() . $this->startKey .'='. $this->totalPages, 307);
            } elseif ($start == '' || $start == '0' || !ctype_digit($start)) {
                $this->redirect(trim($this->prepareQuery(), '&'), 301);
            }
        }

        // fix start,stop
        if ($this->totalRecords == 1) {
            $this->stop = 1;
            $this->start = 0;
        }

        return [$this->stop, $this->start];
    }
988931
protected function recursive_get_all_children($classname, array &$result) {
        foreach ($this->children as $child) {
            if (is_a($child, $classname)) {
                $result[] = $child;
            }
            if ($child instanceof tree) {
                $child->recursive_get_all_children($classname, $result);
            }
        }
    }
424355
public function getChildNodes($dsId, $level = 1)
    {
        $children = [];

        $childrenDsIds = $this->getChildrenDsIds($dsId, $level);
        foreach ($childrenDsIds as $childDsId) {
            $children[] = $this->getNode($childDsId);
        }

        return $children;
    }
495357
public function findChildren(callable $callback, $depth = null, $level = null)
    {

        $level = $level ?: 0;

        foreach ($this->children as $child) {

            /** @var NodeInterface $child */
            if ($child->is($callback))
                yield $child;

            if ($depth === null || $level < $depth) {

                if ($child instanceof NodeInterface)
                    foreach ($child->findChildren($callback, $depth, $level + 1) as $subChild)
                        yield $subChild;
            }
        }
    }
1303642
function _buildTree(&$rootDoc, &$class, $depth = NULL) {
        if ($depth === NULL) {
            $start = TRUE;
            $depth = 0;
        } else {
            $start = FALSE;
        }
        $output = "";
        $undefinedClass = FALSE;
        if ($class->superclass()) {
            $superclass = & $rootDoc->classNamed($class->superclass());
            if ($superclass) {
                $result = $this->_buildTree($rootDoc, $superclass, $depth);
                $output .= $result[0];
                $depth = ++$result[1];
            } else {
                $output .= $class->superclass();
                $output .= " &gt; ";
                $depth++;
                $undefinedClass = TRUE;
            }
        }
        if ($depth > 0 && !$undefinedClass) {
            $output .= " &gt; ";
        }
        if ($start) {
            $output .= "**" . $class->name() . "**\n";
        } else {
            $output .= "<a href=\"" . $this->_asURL($class) . "\">" . $class->name() . "</a>\n";
        }
        return array($output, $depth);
    }
453989
public function begin(string $level, string $message, array $context = []) {
        $output = $this->compareLevel($level, $this->getMinLevel()) >= 0;
        $context = [self::FIELD_BEGIN => true] + $context + [self::FIELD_TIME => microtime(true)];
        $task = [$level, $message, $context, $output];

        if ($output) {
            $this->log($level, $message, $context);
        }

        array_push($this->taskStack, $task);

        return $this;
    }
1005467
public function getList(PageInterface $current = null, $level = 0, $rawRoutes = false, $showAll = true, $showFullpath = false, $showSlug = false, $showModular = false, $limitLevels = false)
    {
        if (!$current) {
            if ($level) {
                throw new \RuntimeException('Internal error');
            }

            $current = $this->root();
        }

        $list = [];

        if (!$current->root()) {
            if ($rawRoutes) {
                $route = $current->rawRoute();
            } else {
                $route = $current->route();
            }

            if ($showFullpath) {
                $option = $current->route();
            } else {
                $extra  = $showSlug ? '(' . $current->slug() . ') ' : '';
                $option = str_repeat('&mdash;-', $level). '&rtrif; ' . $extra . $current->title();


            }

            $list[$route] = $option;


        }

        if ($limitLevels === false || ($level+1 < $limitLevels)) {
            foreach ($current->children() as $next) {
                if ($showAll || $next->routable() || ($next->modular() && $showModular)) {
                    $list = array_merge($list, $this->getList($next, $level + 1, $rawRoutes, $showAll, $showFullpath, $showSlug, $showModular, $limitLevels));
                }
            }
        }

        return $list;
    }
724839
static function subTreeCountByNodeID( $params = array(), $nodeID )
    {
        if ( !is_numeric( $nodeID ) and !is_array( $nodeID ) )
        {
            return null;
        }

        $language = ( isset( $params['Language'] ) ) ? $params['Language'] : false;

        if ( $language )
        {
            if ( !is_array( $language ) )
            {
                $language = array( $language );
            }
            eZContentLanguage::setPrioritizedLanguages( $language );
        }

        $depth         = isset( $params['Depth'] ) && is_numeric( $params['Depth'] ) ? $params['Depth']              : false;
        $depthOperator = isset( $params['DepthOperator'] )                           ? $params['DepthOperator']      : false;

        $pathStringCond     = '';
        $notEqParentString  = '';
        // If the node(s) doesn't exist we return null.
        if ( !eZContentObjectTreeNode::createPathConditionAndNotEqParentSQLStrings( $pathStringCond, $notEqParentString, $nodeID, $depth, $depthOperator ) )
        {
            return null;
        }

        $db = eZDB::instance();
        $ini = eZINI::instance();

        // Check for class filtering
        $classCondition = '';

        if ( isset( $params['ClassFilterType'] ) and isset( $params['ClassFilterArray'] ) and
             ( $params['ClassFilterType'] == 'include' or $params['ClassFilterType'] == 'exclude' )
             and count( $params['ClassFilterArray'] ) > 0 )
        {
            $classCondition = '  ';
            $i = 0;
            $classCount = count( $params['ClassFilterArray'] );
            $classIDArray = array();
            foreach ( $params['ClassFilterArray'] as $classID )
            {
                $originalClassID = $classID;
                // Check if classes are recerenced by identifier
                if ( is_string( $classID ) && !is_numeric( $classID ) )
                {
                    $classID = eZContentClass::classIDByIdentifier( $classID );
                }
                if ( is_numeric( $classID ) )
                {
                    $classIDArray[] = $classID;
                }
                else
                {
                    eZDebugSetting::writeWarning( 'kernel-content-class', "Invalid class identifier in subTree() classfilterarray, classID : " . $originalClassID );
                }
            }
            if ( count( $classIDArray ) > 0  )
            {
                $classCondition .= " ezcontentobject.contentclass_id ";
                if ( $params['ClassFilterType'] == 'include' )
                    $classCondition .= " IN ";
                else
                    $classCondition .= " NOT IN ";

                $classIDString =  implode( ', ', $classIDArray );
                $classCondition .= ' ( ' . $classIDString . ' ) AND';
            }
        }


        // Main node check
        $mainNodeOnlyCond = '';
        if ( isset( $params['MainNodeOnly'] ) && $params['MainNodeOnly'] === true )
        {
            $mainNodeOnlyCond = 'ezcontentobject_tree.node_id = ezcontentobject_tree.main_node_id AND';
        }

        $languageFilter = ' AND '.eZContentLanguage::languagesSQLFilter( 'ezcontentobject' );
        $objectNameLanguageFilter = eZContentLanguage::sqlFilter( 'ezcontentobject_name', 'ezcontentobject' );

        if ( $language )
        {
            eZContentLanguage::clearPrioritizedLanguages();
        }
        $objectNameFilter = ( isset( $params['ObjectNameFilter']  ) ) ? $params['ObjectNameFilter']   : false;

        $attributeFilterParam = isset( $params['AttributeFilter'] ) ? $params['AttributeFilter'] : false;
        $sortingInfo = array( 'sortCount' => 0, 'attributeJoinCount' => 0 );
        $attributeFilter = eZContentObjectTreeNode::createAttributeFilterSQLStrings( $attributeFilterParam, $sortingInfo, $language );
        if ( $attributeFilter === false )
        {
            return null;
        }
        $objectNameFilterSQL = eZContentObjectTreeNode::createObjectNameFilterConditionSQLString( $objectNameFilter );

        $extendedAttributeFilter = eZContentObjectTreeNode::createExtendedAttributeFilterSQLStrings( $params['ExtendedAttributeFilter'] );

        // Determine whether we should show invisible nodes.
        $ignoreVisibility = isset( $params['IgnoreVisibility'] ) ? $params['IgnoreVisibility'] : false;
        $showInvisibleNodesCond = eZContentObjectTreeNode::createShowInvisibleSQLString( !$ignoreVisibility );

        $limitation = ( isset( $params['Limitation']  ) && is_array( $params['Limitation']  ) ) ? $params['Limitation']: false;
        $limitationList = eZContentObjectTreeNode::getLimitationList( $limitation );
        $sqlPermissionChecking = eZContentObjectTreeNode::createPermissionCheckingSQL( $limitationList );

        $query = "SELECT
                        count( DISTINCT ezcontentobject_tree.node_id ) as count
                  FROM
                       ezcontentobject_tree
                       INNER JOIN ezcontentobject ON (ezcontentobject.id = ezcontentobject_tree.contentobject_id)
                       INNER JOIN ezcontentclass ON (ezcontentclass.id = ezcontentobject.contentclass_id)
                       INNER JOIN ezcontentobject_name ON (
                           ezcontentobject_name.contentobject_id = ezcontentobject_tree.contentobject_id AND
                           ezcontentobject_name.content_version = ezcontentobject_tree.contentobject_version
                       )
                       $attributeFilter[from]
                       $extendedAttributeFilter[tables]
                       $sqlPermissionChecking[from]
                  WHERE $pathStringCond
                        $extendedAttributeFilter[joins]
                        $mainNodeOnlyCond
                        $classCondition
                        $attributeFilter[where]
                        ezcontentclass.version=0 AND
                        $notEqParentString
                        $objectNameLanguageFilter
                        $showInvisibleNodesCond
                        $sqlPermissionChecking[where]
                        $objectNameFilterSQL
                        $languageFilter ";

        $server = count( $sqlPermissionChecking['temp_tables'] ) > 0 ? eZDBInterface::SERVER_SLAVE : false;

        $nodeListArray = $db->arrayQuery( $query, array(), $server );

        // cleanup temp tables
        $db->dropTempTableList( $sqlPermissionChecking['temp_tables'] );

        return $nodeListArray[0]['count'];
    }
1346567
private function getAllChildKeys($data, $maps, $parent_keys, $parent_types, & $result, & $keys, $current_key = [], $current_type = null) {
		if ($current_type == '11') {
			$data = ['__11__' => $data];
		}
		foreach ($data as $k => $v) {
			$new_key = $current_key;
			if ($current_type != '11') {
				$new_key[] = $k;
			}
			if (count($parent_keys) == 1) {
				$new_key[] = $parent_keys[0];
				// put values into result
				$result[] = $new_key;
				// generate keys
				$temp = [];
				foreach ($maps[0] as $k3 => $v3) {
					$temp[] = $v[$k3];
				}
				// we need to preserve a data type if its just one column key
				if (count($temp) == 1) {
					$keys[] = $temp[0];
				} else {
					$keys[] = implode('::', $temp);
				}
			} else {
				// remove extra level
				$parent_keys_temp = $parent_keys;
				$v2 = array_shift($parent_keys_temp);
				$parent_types_temp = $parent_types;
				array_shift($parent_types_temp);
				$maps_temp = $maps;
				array_shift($maps_temp);
				// generate key
				$new_key[] = $v2;
				$this->getAllChildKeys($v[$v2], $maps_temp, $parent_keys_temp, $parent_types_temp, $result, $keys, $new_key, $parent_types[0]);
			}
		}
	}
8841
private static void getAllDescendants(
        TreeModel treeModel, Object node, List<Object> result)
    {
        if (node == null)
        {
            return;
        }
        result.add(node);
        List<Object> children = getChildren(treeModel, node);
        for (Object child : children)
        {
            getAllDescendants(treeModel, child, result);
        }
    }
369840
public function diff($start, $end, $level = 'MB')
    {
        $startPoint = $this->getPoint($start);
        $endPoint   = $this->getPoint($end);

        return [
            'time'   => $endPoint['time'] - $startPoint['time'],
            'memory' => ($endPoint['memory'] - $startPoint['memory']) / pow(1024, (int) array_search($level, $this->memoryLevel))
        ];
    }
566462
public function findPlaceholders(array $placeholders = [], $recursive = false)
    {
        if (empty($placeholders)) {
            return [];
        }
        $result = [];
        foreach ($placeholders as $name => $value) {
            if (is_int($name)) {

                if ($this->existsPlaceholder($value)) {

                    $result[$this->_prepareNamePlaceholder($value)] = $this->getPlaceholder($value, false);
                } elseif ($recursive) {
                    /** @var static $scope */
                    foreach (array_reverse($this->scopes, true) as $scope) {
                        if ($scope->existsPlaceholder($value)) {
                            $result[$this->_prepareNamePlaceholder($value)] = $scope->getPlaceholder($value);
                            break;
                        }
                    }
                }
                continue;
            }
            $result[$name] = $value;
        }

        return $result;
    }
699364
public static function nodesTreeList($parentId = 0, $level = 0, $shiftPrefix = '. ')
    {
        if (!isset(static::$_nodesTreeList[$parentId][$level][$shiftPrefix])) {
            $tree = [];
            $list = [];

            $parentNode = static::node($parentId);
            if (!empty($parentNode)) {
                $grandParentId = $parentNode['parent_id'];
                $grandParentNode = static::node($grandParentId);
                $nodePath = (empty($grandParentNode->nodePath)
                             ? '' : $grandParentNode->nodePath . '/'
                         ) . $parentNode['slug'];
                $list[$parentId] = str_repeat($shiftPrefix, $level) . $nodePath;
                $tree[$parentId] = str_repeat($shiftPrefix, $level) . $parentNode['slug'];
                static::saveNodePath($parentId, $nodePath);
            }

            $children = static::nodeChildren($parentId);
            foreach ($children as $child) {
                static::$_nodes[$child['id']] = $child;
                $list += static::nodesTreeList($child->id, $level+1, $shiftPrefix);
                $tree += static::nodesTree($child->id, $level+1, $shiftPrefix);
            }
            static::$_nodesTree[$parentId][$level][$shiftPrefix] = $tree;
            static::$_nodesTreeList[$parentId][$level][$shiftPrefix] = $list;
        }    
        return static::$_nodesTreeList[$parentId][$level][$shiftPrefix];
    }
50266
protected function _createTree( MW_DB_Result_Interface $result, MW_Tree_Node_Interface $node )
	{
		while( ( $record = $result->fetch() ) !== false )
		{
			$newNode = $this->_createNode( $record );

			while( $this->_isChild( $newNode, $node ) )
			{
				$node->addChild( $newNode );

				if( ( $newNode = $this->_createTree( $result, $newNode ) ) === false ) {
					return false;
				}
			}

			return $newNode;
		}

		return false;
	}