View source
<?php
namespace Drupal\views_tree;
use Drupal\Core\Template\Attribute;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
class TreeHelper {
protected $treeValues;
public function __construct(ViewsResultTreeValues $tree_values) {
$this->treeValues = $tree_values;
}
public function buildRenderTree(ViewExecutable $view, array $rows) {
$result = $view->result;
$this->treeValues
->setTreeValues($view, $result);
$result_tree = $this
->getTreeFromResult($result);
return $this
->applyFunctionToTree($result_tree, function (ResultRow $row) use ($rows) {
return $rows[$row->index];
});
}
public function addDataAttributes(TreeItem $tree, $nesting = 0) {
$node = $tree
->getNode();
if (isset($node['attributes']) && $node['attributes'] instanceof Attribute) {
$node['attributes']
->setAttribute('data-hierarchy-level', $nesting);
}
$nesting++;
foreach ($tree
->getLeaves() as $leaf) {
$this
->addDataAttributes($leaf, $nesting);
}
}
public function getTreeFromResult(array $result) {
$groups = $this
->groupResultByParent($result);
return $this
->getTreeFromGroups($groups);
}
protected function getTreeFromGroups(array $groups, $current_group = '0') {
$return = new TreeItem(NULL);
if (empty($groups[$current_group])) {
return $return;
}
foreach ($groups[$current_group] as $item) {
$tree_item = new TreeItem($item);
$return
->addLeave($tree_item);
$tree_item
->setLeaves($this
->getTreeFromGroups($groups, $item->views_tree_main)
->getLeaves());
}
return $return;
}
protected function groupResultByParent(array $result) {
$return = [];
foreach ($result as $row) {
$return[$row->views_tree_parent][] = $row;
}
return $return;
}
public function applyFunctionToTree(TreeItem $tree, callable $callable) {
if (($node = $tree
->getNode()) && $node !== NULL) {
$new_node = $callable($tree
->getNode());
}
else {
$new_node = NULL;
}
$new_tree = new TreeItem($new_node);
foreach ($tree
->getLeaves() as $leave) {
$new_tree
->addLeave($this
->applyFunctionToTree($leave, $callable));
}
return $new_tree;
}
}