MenuTrailByPathActiveTrail.php in Menu Trail By Path 8
File
src/MenuTrailByPathActiveTrail.php
View source
<?php
namespace Drupal\menu_trail_by_path;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Menu\MenuActiveTrail;
use Drupal\Core\Menu\MenuLinkManagerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\menu_trail_by_path\Menu\MenuHelperInterface;
use Drupal\menu_trail_by_path\Path\PathHelperInterface;
use Drupal\Core\Routing\RequestContext;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\system\Entity\Menu;
class MenuTrailByPathActiveTrail extends MenuActiveTrail {
const MENU_TRAIL_DISABLED = 'disabled';
const MENU_TRAIL_PATH = 'path';
const MENU_TRAIL_CORE = 'core';
protected $pathHelper;
protected $menuHelper;
protected $context;
protected $languageManager;
protected $config;
public function __construct(MenuLinkManagerInterface $menu_link_manager, RouteMatchInterface $route_match, CacheBackendInterface $cache, LockBackendInterface $lock, PathHelperInterface $path_helper, MenuHelperInterface $menu_helper, RequestContext $context, LanguageManagerInterface $languageManager, ConfigFactoryInterface $config_factory) {
parent::__construct($menu_link_manager, $route_match, $cache, $lock);
$this->pathHelper = $path_helper;
$this->menuHelper = $menu_helper;
$this->context = $context;
$this->languageManager = $languageManager;
$this->config = $config_factory
->get('menu_trail_by_path.settings');
}
protected function getCid() {
if (!isset($this->cid)) {
return parent::getCid() . ":langcode:{$this->languageManager->getCurrentLanguage()->getId()}:pathinfo:{$this->context->getPathInfo()}";
}
return $this->cid;
}
protected function doGetActiveTrailIds($menu_name) {
$active_trail = array(
'' => '',
);
$entity = Menu::load($menu_name);
if (!$entity) {
return $active_trail;
}
$trail_source = $entity
->getThirdPartySetting('menu_trail_by_path', 'trail_source') ?: $this->config
->get('trail_source');
if ($trail_source == static::MENU_TRAIL_CORE) {
return parent::doGetActiveTrailIds($menu_name);
}
elseif ($trail_source == static::MENU_TRAIL_DISABLED) {
return $active_trail;
}
if ($active_link = $this
->getActiveTrailLink($menu_name)) {
if ($parents = $this->menuLinkManager
->getParentIds($active_link
->getPluginId())) {
$active_trail = $parents + $active_trail;
}
}
return $active_trail;
}
public function getActiveTrailLink($menu_name) {
$menu_links = $this->menuHelper
->getMenuLinks($menu_name);
$trail_urls = $this->pathHelper
->getUrls();
foreach (array_reverse($trail_urls) as $trail_url) {
foreach (array_reverse($menu_links) as $menu_link) {
if ($menu_link
->getUrlObject()
->toString() == $trail_url
->toString()) {
return $menu_link;
}
}
}
return NULL;
}
}