MediaDirectoriesTreeBuilder.php in Media Directories 3.x
File
modules/media_directories_ui/src/MediaDirectoriesTreeBuilder.php
View source
<?php
namespace Drupal\media_directories_ui;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
class MediaDirectoriesTreeBuilder {
use StringTranslationTrait;
protected $configFactory;
protected $entityTypeManager;
protected $termStorage;
protected $vocabulary_id;
public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager) {
$this->configFactory = $config_factory;
$this->entityTypeManager = $entity_type_manager;
$config = $this->configFactory
->get('media_directories.settings');
$this->vocabulary_id = $config
->get('directory_taxonomy');
}
public function tree() {
$tree = [];
$this->termStorage = $this->entityTypeManager
->getStorage('taxonomy_term');
$terms = $this->termStorage
->loadTree($this->vocabulary_id);
foreach ($terms as $term) {
$this
->buildTree($tree, $term, $this->vocabulary_id);
}
$tree = [
[
'id' => 'dir-root',
'text' => $this
->t('Root'),
'state' => [
'opened' => TRUE,
'selected' => TRUE,
],
'a_attr' => [
'data-tid' => MEDIA_DIRECTORY_ROOT,
],
'children' => array_values($tree),
],
];
return $tree;
}
protected function buildTree(&$tree, $object, $vocabulary) {
if ($object->depth !== 0) {
return;
}
$tree[$object->tid] = $object;
$tree[$object->tid]->children = [];
$tree[$object->tid]->text = $object->name;
$tree[$object->tid]->a_attr = [
'data-tid' => $object->tid,
];
$tree[$object->tid]->id = 'dir-' . $object->tid;
$object_children =& $tree[$object->tid]->children;
$children = $this->termStorage
->loadChildren($object->tid);
if (!$children) {
return;
}
$child_tree_objects = $this->termStorage
->loadTree($vocabulary, $object->tid);
foreach ($children as $child) {
foreach ($child_tree_objects as $child_tree_object) {
if ($child_tree_object->tid === $child
->id()) {
$this
->buildTree($object_children, $child_tree_object, $vocabulary);
}
}
}
$tree[$object->tid]->children = array_values($tree[$object->tid]->children);
}
}