AddMenuOverride.php in Entity Reference Hierarchy 3.x
File
modules/entity_hierarchy_microsite/src/Controller/AddMenuOverride.php
View source
<?php
namespace Drupal\entity_hierarchy_microsite\Controller;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Menu\MenuLinkManagerInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class AddMenuOverride implements ContainerInjectionInterface {
private $entityFormBuilder;
private $menuLinkManager;
private $entityTypeManager;
public function __construct(EntityFormBuilderInterface $entityFormBuilder, MenuLinkManagerInterface $menuLinkManager, EntityTypeManagerInterface $entityTypeManager) {
$this->entityFormBuilder = $entityFormBuilder;
$this->menuLinkManager = $menuLinkManager;
$this->entityTypeManager = $entityTypeManager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity.form_builder'), $container
->get('plugin.manager.menu.link'), $container
->get('entity_type.manager'));
}
public function addMenuOverride(string $target) {
$plugin_id = 'entity_hierarchy_microsite:' . $target;
if (!$this->menuLinkManager
->hasDefinition($plugin_id)) {
throw new NotFoundHttpException();
}
$storage = $this->entityTypeManager
->getStorage('eh_microsite_menu_override');
if ($storage
->loadByProperties([
'target' => $target,
])) {
throw new NotFoundHttpException();
}
$instance = $this->menuLinkManager
->createInstance($plugin_id);
$override = $storage
->create([
'target' => $target,
'enabled' => $instance
->isEnabled(),
'weight' => $instance
->getWeight(),
'title' => $instance
->getTitle(),
'parent' => $instance
->getParent(),
]);
return $this->entityFormBuilder
->getForm($override);
}
public function title(string $target) {
$plugin_id = 'entity_hierarchy_microsite:' . $target;
if (!$this->menuLinkManager
->hasDefinition($plugin_id)) {
return '';
}
$instance = $this->menuLinkManager
->createInstance($plugin_id);
return new TranslatableMarkup('Add an override for @label', [
'@label' => $instance
->getTitle(),
]);
}
}