CurrentPathHelper.php in Menu Trail By Path 8
File
src/Path/CurrentPathHelper.php
View source
<?php
namespace Drupal\menu_trail_by_path\Path;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Routing\RequestContext;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
class CurrentPathHelper implements PathHelperInterface {
protected $routeMatch;
protected $config;
private $context;
public function __construct(RouteMatchInterface $route_match, RequestContext $context, ConfigFactoryInterface $config_factory) {
$this->routeMatch = $route_match;
$this->context = $context;
$this->config = $config_factory
->get('menu_trail_by_path.settings');
}
public function getUrls() {
$trail_urls = $this
->getCurrentPathUrls();
if ($current_request_url = $this
->getCurrentRequestUrl()) {
$trail_urls[] = $current_request_url;
}
return $trail_urls;
}
protected function getCurrentRequestUrl() {
$current_pathinfo_url = $this
->createUrlFromRelativeUri($this->context
->getPathInfo());
if ($current_pathinfo_url
->isRouted()) {
return $current_pathinfo_url;
}
elseif ($route_name = $this->routeMatch
->getRouteName()) {
$route_parameters = $this->routeMatch
->getRawParameters()
->all();
return new Url($route_name, $route_parameters);
}
return NULL;
}
public function getPathElements() {
$path = trim($this->context
->getPathInfo(), '/');
$path_elements = explode('/', $path);
if (is_array($path_elements) && ($max_path_parts = $this->config
->get('max_path_parts'))) {
return array_splice($path_elements, 0, $max_path_parts);
}
return $path_elements;
}
protected function getCurrentPathUrls() {
$urls = [];
$path_elements = $this
->getPathElements();
while (count($path_elements) > 1) {
array_pop($path_elements);
$url = $this
->createUrlFromRelativeUri('/' . implode('/', $path_elements));
if ($url
->isRouted()) {
$urls[] = $url;
}
}
return array_reverse($urls);
}
protected function createUrlFromRelativeUri($relativeUri) {
if (UrlHelper::isExternal(substr($relativeUri, 1))) {
return Url::fromUri('base:' . $relativeUri);
}
$relativeUri = str_replace('//', '/', $relativeUri);
return Url::fromUserInput($relativeUri);
}
}