MenuBuilder.php in Context 8.4
File
modules/context_ui/src/MenuBuilder.php
View source
<?php
namespace Drupal\context_ui;
use Drupal\context\Entity\Context;
use Drupal\Core\Menu\MenuLinkManagerInterface;
use Drupal\Core\Url;
use Drupal\menu_link_content\Entity\MenuLinkContent;
class MenuBuilder {
protected $menuLinkManager;
public function __construct(MenuLinkManagerInterface $menuLinkManager) {
$this->menuLinkManager = $menuLinkManager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('plugin.manager.menu.link'));
}
public function addSubMenuItem(Context $entity) {
$menu_link = MenuLinkContent::create([
'title' => $entity
->getLabel(),
'link' => $this
->getUriString($entity),
'menu_name' => 'admin',
'parent' => 'entity.context.collection',
'expanded' => TRUE,
'weight' => 10,
]);
$menu_link
->save();
$this->menuLinkManager
->rebuild();
}
public function updateSubMenuItem(Context $entity) {
$result = $this->menuLinkManager
->loadLinksByRoute('entity.context.edit_form', [
'context' => $entity
->id(),
]);
if (!empty($result)) {
foreach ($result as $id => $instance) {
if (strpos($id, 'menu_link_content:') === 0) {
$instance
->updateLink([
'title' => $entity
->getLabel(),
'link' => $this
->getUriString($entity),
], TRUE);
}
}
$this->menuLinkManager
->rebuild();
}
else {
$this
->addSubMenuItem($entity);
}
}
public function deleteSubMenuItem(Context $entity) {
$result = $this->menuLinkManager
->loadLinksByRoute('entity.context.edit_form', [
'context' => $entity
->id(),
]);
if (!empty($result)) {
foreach ($result as $id => $instance) {
if ($instance
->isDeletable() && strpos($id, 'menu_link_content:') === 0) {
$instance
->deleteLink();
$this->menuLinkManager
->rebuild();
}
}
}
$this->menuLinkManager
->rebuild();
}
private function getUriString(Context $entity) {
$url = Url::fromRoute('entity.context.edit_form', [
'context' => $entity
->id(),
]);
return $url
->toUriString();
}
}