Skip to content

Instantly share code, notes, and snippets.

@mmoreram
Last active December 21, 2015 10:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmoreram/6292326 to your computer and use it in GitHub Desktop.
Save mmoreram/6292326 to your computer and use it in GitHub Desktop.
Doctrine2 Entity tree builder O(n)
<?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