WorkspaceRepository.php in Drupal 9
File
core/modules/workspaces/src/WorkspaceRepository.php
View source
<?php
namespace Drupal\workspaces;
use Drupal\Component\Graph\Graph;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class WorkspaceRepository implements WorkspaceRepositoryInterface {
protected $entityTypeManager;
protected $cache;
protected $tree;
public function __construct(EntityTypeManagerInterface $entity_type_manager, CacheBackendInterface $cache_backend) {
$this->entityTypeManager = $entity_type_manager;
$this->cache = $cache_backend;
}
public function loadTree() {
if (!isset($this->tree)) {
$cache = $this->cache
->get('workspace_tree');
if ($cache) {
$this->tree = $cache->data;
return $this->tree;
}
$workspaces = $this->entityTypeManager
->getStorage('workspace')
->loadMultiple();
uasort($workspaces, function (WorkspaceInterface $a, WorkspaceInterface $b) {
return strnatcasecmp($a
->label(), $b
->label());
});
$tree_children = [];
foreach ($workspaces as $workspace_id => $workspace) {
$tree_children[$workspace->parent->target_id][] = $workspace_id;
}
$process_parents[] = NULL;
$tree = [];
while (count($process_parents)) {
$parent = array_pop($process_parents);
if (!empty($tree_children[$parent])) {
$child_id = current($tree_children[$parent]);
do {
if (empty($child_id)) {
break;
}
$tree[$child_id] = $workspaces[$child_id];
if (!empty($tree_children[$child_id])) {
$process_parents[] = $parent;
$process_parents[] = $child_id;
next($tree_children[$parent]);
break;
}
} while ($child_id = next($tree_children[$parent]));
}
}
$graph = [];
foreach ($workspaces as $workspace_id => $workspace) {
$graph[$workspace_id]['edges'] = [];
if (!$workspace->parent
->isEmpty()) {
$graph[$workspace_id]['edges'][$workspace->parent->target_id] = TRUE;
}
}
$graph = (new Graph($graph))
->searchAndSort();
foreach (array_keys($tree) as $workspace_id) {
$this->tree[$workspace_id] = [
'depth' => count($graph[$workspace_id]['paths']),
'ancestors' => array_keys($graph[$workspace_id]['paths']),
'descendants' => isset($graph[$workspace_id]['reverse_paths']) ? array_keys($graph[$workspace_id]['reverse_paths']) : [],
];
}
$this->cache
->set('workspace_tree', $this->tree, Cache::PERMANENT, $this->entityTypeManager
->getDefinition('workspace')
->getListCacheTags());
}
return $this->tree;
}
public function getDescendantsAndSelf($workspace_id) {
return array_merge([
$workspace_id,
], $this
->loadTree()[$workspace_id]['descendants']);
}
public function resetCache() {
$this->tree = NULL;
return $this;
}
}