View source
<?php
namespace Drupal\menu_link_weight\MenuParentFormSelector;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Menu\MenuParentFormSelector;
use Drupal\Core\Menu\MenuTreeParameters;
class CshsMenuParentFormSelector extends MenuParentFormSelector {
public function getParentSelectOptionsCshs($id = '', array $menus = NULL, CacheableMetadata &$cacheability = NULL) {
if (!isset($menus)) {
$menus = $this
->getMenuOptions();
}
$options = [];
$depth_limit = $this
->getParentDepthLimit($id);
foreach ($menus as $menu_name => $menu_title) {
$options[$menu_name . ':'] = [
'name' => '<' . $menu_title . '>',
'parent_tid' => 0,
];
$parameters = new MenuTreeParameters();
$parameters
->setMaxDepth($depth_limit);
$tree = $this->menuLinkTree
->load($menu_name, $parameters);
$manipulators = [
[
'callable' => 'menu.default_tree_manipulators:checkNodeAccess',
],
[
'callable' => 'menu.default_tree_manipulators:checkAccess',
],
[
'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
],
];
$tree = $this->menuLinkTree
->transform($tree, $manipulators);
$this
->parentSelectOptionsTreeWalkCshs($tree, $menu_name, $menu_name . ':', $options, $id, $depth_limit, $cacheability);
}
return $options;
}
public function parentSelectElement($menu_parent, $id = '', array $menus = NULL) {
$options_cacheability = new CacheableMetadata();
$options = $this
->getParentSelectOptionsCshs($id, $menus, $options_cacheability);
if ($options) {
$element = [
'#type' => 'cshs',
'#options' => $options,
'#attached' => [
'library' => [
'menu_link_weight/menu_parent_selector.cshs',
],
],
];
if (!isset($options[$menu_parent])) {
list($menu_name, $parent) = explode(':', $menu_parent, 2);
$menu_parent = $menu_name . ':';
}
if (isset($options[$menu_parent])) {
$element += [
'#default_value' => $menu_parent,
];
}
$options_cacheability
->applyTo($element);
return $element;
}
return [];
}
protected function parentSelectOptionsTreeWalkCshs(array $tree, $menu_name, $indent, array &$options, $exclude, $depth_limit, CacheableMetadata &$cacheability = NULL) {
foreach ($tree as $element) {
if ($element->depth > $depth_limit) {
break;
}
if ($cacheability) {
$cacheability = $cacheability
->merge(CacheableMetadata::createFromObject($element->access))
->merge(CacheableMetadata::createFromObject($element->link));
}
if (!$element->access
->isAllowed()) {
continue;
}
$link = $element->link;
if ($link
->getPluginId() != $exclude) {
$title = Unicode::truncate($link
->getTitle(), 30, TRUE, FALSE);
if (!$link
->isEnabled()) {
$title .= ' (' . $this
->t('disabled') . ')';
}
$options[$menu_name . ':' . $link
->getPluginId()] = [
'name' => $title,
'parent_tid' => $indent,
];
if (!empty($element->subtree)) {
$this
->parentSelectOptionsTreeWalkCshs($element->subtree, $menu_name, $menu_name . ':' . $link
->getPluginId(), $options, $exclude, $depth_limit, $cacheability);
}
}
}
}
}