LanguagePathSubscriber.php in Tome 8
File
modules/tome_static/src/EventSubscriber/LanguagePathSubscriber.php
View source
<?php
namespace Drupal\tome_static\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl;
use Drupal\tome_base\PathTrait;
use Drupal\tome_static\Event\CollectPathsEvent;
use Drupal\tome_static\Event\TomeStaticEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LanguagePathSubscriber implements EventSubscriberInterface {
use PathTrait;
protected $languageManager;
protected $configFactory;
public function __construct(ConfigFactoryInterface $config_factory, LanguageManagerInterface $language_manager) {
$this->configFactory = $config_factory;
$this->languageManager = $language_manager;
}
public function collectPaths(CollectPathsEvent $event) {
$config = $this->configFactory
->get('language.negotiation')
->get('url');
if (is_array($config) && isset($config['source'])) {
if ($config['source'] === LanguageNegotiationUrl::CONFIG_PATH_PREFIX) {
foreach ($this->languageManager
->getLanguages() as $language) {
$langcode = $language
->getId();
if (!empty($config['prefixes'][$langcode])) {
$prefix = $this
->joinPaths('/', $config['prefixes'][$langcode]);
$event
->addPath($prefix, [
'language_processed' => 'language_processed',
]);
foreach ($event
->getPaths(TRUE) as $path => $metadata) {
if (!isset($metadata['language_processed']) && (!isset($metadata['language_prefix']) || $metadata['language_prefix'] === $langcode)) {
if (!isset($metadata['original_path'])) {
$metadata['original_path'] = $path;
}
$metadata['language_processed'] = 'language_processed';
if (isset($metadata['language_prefix'])) {
$event
->replacePath($path, $this
->joinPaths($prefix, $path), $metadata);
}
else {
$event
->addPath($this
->joinPaths($prefix, $path), $metadata);
}
}
}
}
}
}
elseif ($config['source'] === LanguageNegotiationUrl::CONFIG_DOMAIN) {
$paths = $event
->getPaths(TRUE);
foreach ($paths as $path => $metadata) {
if (isset($metadata['language_processed']) && isset($metadata['langcode'])) {
if ($metadata['langcode'] !== $this->languageManager
->getCurrentLanguage()
->getId()) {
unset($paths[$path]);
}
}
}
$event
->replacePaths($paths);
}
}
}
public static function getSubscribedEvents() {
$events[TomeStaticEvents::COLLECT_PATHS][] = [
'collectPaths',
-1,
];
return $events;
}
}