Last active
December 21, 2015 10:29
-
-
Save mmoreram/6292326 to your computer and use it in GitHub Desktop.
Doctrine2 Entity tree builder O(n)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Cost O(n) | |
* | |
* This method allow build a tree given following data | |
* | |
* $entities is an Array ( or any ArrayIterator implementation ) of $entity | |
* $entity is an Object ( can be Whatever ) | |
* | |
* In this case: | |
* $entity implements isRoot() what defines if entity is first level | |
* $entity implements getParent(), a doctrine relation with a parent Entity | |
*/ | |
$tree = array( | |
0 => null, | |
'children' => array(), | |
); | |
/* | |
* Iterating every entity | |
*/ | |
foreach (entities as $entity) { | |
$parentEntityId = 0; | |
entityId = $entity->getId(); | |
/** | |
* If is not root, we need to load parent id without lazy loading it | |
* Otherwise, is 0 ( root ) | |
*/ | |
if (!$entity->isRoot()) { | |
$parentEntityId = $this | |
->getDoctrine() | |
->getManager() | |
->getUnitOfWork() | |
->getEntityIdentifier($category->getParent())['id']; | |
} | |
/** | |
* Initizalizing parent block | |
*/ | |
if (!isset($tree[$parentEntityId])) { | |
$tree[$parentEntityId] = array( | |
'entity' => null, | |
'children' => array(), | |
); | |
} | |
/** | |
* Initializing entity block | |
*/ | |
if (!isset($tree[$entityId])) { | |
$tree[$entityId] = array( | |
'entity' => null, | |
'children' => array(), | |
); | |
} | |
/** | |
* Setting entity and adding it to parent children | |
* Using pointer to fast access to entity for future children | |
*/ | |
$tree[$entityId]['entity'] = $entity; | |
$tree[$parentEntityId]['children'][] = &$tree[$entityId]; | |
} | |
/** | |
* Full tree is available by getting root children array | |
*/ | |
$tree = $tree[0]['children']; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment