SingleLanguageNegotiationUrl.php in Single Language URL Prefix 8
File
src/SingleLanguageNegotiationUrl.php
View source
<?php
namespace Drupal\single_language_url_prefix;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Path\PathMatcherInterface;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl;
use Symfony\Component\HttpFoundation\Request;
class SingleLanguageNegotiationUrl implements InboundPathProcessorInterface, OutboundPathProcessorInterface {
protected $languageManager;
protected $config;
protected $pathMatcher;
protected $excludedPaths = NULL;
public function __construct(LanguageManagerInterface $language_manager, ConfigFactoryInterface $config, PathMatcherInterface $path_matcher) {
$this->languageManager = $language_manager;
$this->config = $config;
$this->pathMatcher = $path_matcher;
}
public function processInbound($path, Request $request) {
$languages = $this->languageManager
->getLanguages();
if (count($languages) > 1 || $this
->isPathExcluded($path)) {
return $path;
}
$config = $this->config
->get('language.negotiation')
->get('url');
$source = $config['source'] ?? '';
if ($source === LanguageNegotiationUrl::CONFIG_PATH_PREFIX) {
$parts = explode('/', trim($path, '/'));
$prefix = array_shift($parts);
$language = reset($languages);
if (isset($config['prefixes'][$language
->getId()]) && $config['prefixes'][$language
->getId()] == $prefix) {
$path = '/' . implode('/', $parts);
}
}
return $path;
}
public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
$languages = $this->languageManager
->getLanguages();
if (count($languages) > 1 || $this
->isPathExcluded($path)) {
return $path;
}
$config = $this->config
->get('language.negotiation')
->get('url');
$source = $config['source'] ?? '';
if ($source === LanguageNegotiationUrl::CONFIG_PATH_PREFIX) {
$language = reset($languages);
if (isset($config['prefixes'][$language
->getId()])) {
$options['prefix'] = $config['prefixes'][$language
->getId()] . '/';
}
}
return $path;
}
protected function isPathExcluded($path) {
if (!isset($this->excludedPaths)) {
$config = $this->config
->get('single_language_url_prefix.settings');
$this->excludedPaths = $config
->get('excluded_paths') ?? '';
}
if (empty($this->excludedPaths)) {
return FALSE;
}
return (bool) $this->pathMatcher
->matchPath($path, $this->excludedPaths);
}
}