Skip to content

Instantly share code, notes, and snippets.

@rufinus
Created August 22, 2014 16:03
Show Gist options
  • Save rufinus/99f6808d0b4fe2b51530 to your computer and use it in GitHub Desktop.
Save rufinus/99f6808d0b4fe2b51530 to your computer and use it in GitHub Desktop.
<?php
namespace Cwd\GenericBundle\Repository;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Doctrine\Common\Persistence\ObjectManager;
use Gedmo\Exception\InvalidArgumentException;
use Gedmo\Tree\RepositoryUtils as GedmoRepositoryUtils;
class RepositoryUtils extends GedmoRepositoryUtils
{
/**
* {@inheritDoc}
*/
public function buildTree(array $nodes, array $options = array())
{
$meta = $this->getClassMetadata();
$nestedTree = $this->repo->buildTreeArray($nodes);
$default = array(
'decorate' => false,
'rootOpen' => '<ul>',
'rootClose' => '</ul>',
'childOpen' => '<li>',
'childClose' => '</li>',
'idField' => false,
'nodeDecorator' => function ($node) use ($meta) {
// override and change it, guessing which field to use
if ($meta->hasField('title')) {
$field = 'title';
} elseif ($meta->hasField('name')) {
$field = 'name';
} else {
throw new InvalidArgumentException("Cannot find any representation field");
}
return $node[$field];
}
);
$options = array_merge($default, $options);
// If you don't want any html output it will return the nested array
if (!$options['decorate']) {
return $nestedTree;
}
if (!count($nestedTree)) {
return '';
}
$childrenIndex = $this->childrenIndex;
$build = function($tree) use (&$build, &$options, $childrenIndex, $meta) {
$output = is_string($options['rootOpen']) ? $options['rootOpen'] : $options['rootOpen']($tree);
foreach ($tree as $node) {
$childOpen = is_string($options['childOpen']) ? $options['childOpen'] : $options['childOpen']($node);
$idField = is_string($options['idField']) ? $options['idField'] : $options['idField']($node);
$output .= ($meta->hasField($idField)) ? sprintf($childOpen, $node[$idField]) : $childOpen;
$output .= $options['nodeDecorator']($node);
if (count($node[$childrenIndex]) > 0) {
$output .= $build($node[$childrenIndex]);
}
$output .= is_string($options['childClose']) ? $options['childClose'] : $options['childClose']($node);
}
return $output . (is_string($options['rootClose']) ? $options['rootClose'] : $options['rootClose']($tree));
};
return $build($nestedTree);
}
}
$repo = $this->getService()->getEm()->getRepository('Model:Category');
$arrayTree = $repo->childrenHierarchy(null, false, array(
'decorate' => true,
'representationField' => 'slug',
'html' => true,
'rootOpen' => '<ol class="dd-list">',
'rootClose' => '</ol>',
'childOpen' => '<li class="dd-item" data-id="%s">',
'idField' => 'id',
'childClose' => '</li>',
'nodeDecorator' => function($node) {
return '<div class="dd-handle" data-id="'.$node['id'].'">'.$node['name'].'</div>';
}
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment