LanguageRequestSubscriber.php in Drupal 10
File
core/modules/language/src/EventSubscriber/LanguageRequestSubscriber.php
View source
<?php
namespace Drupal\language\EventSubscriber;
use Drupal\Core\DrupalKernelInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\Translator\TranslatorInterface;
use Drupal\language\ConfigurableLanguageManagerInterface;
use Drupal\language\LanguageNegotiatorInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LanguageRequestSubscriber implements EventSubscriberInterface {
protected $languageManager;
protected $negotiator;
protected $translation;
protected $currentUser;
public function __construct(ConfigurableLanguageManagerInterface $language_manager, LanguageNegotiatorInterface $negotiator, TranslatorInterface $translation, AccountInterface $current_user) {
$this->languageManager = $language_manager;
$this->negotiator = $negotiator;
$this->translation = $translation;
$this->currentUser = $current_user;
}
public function onKernelRequestLanguage(RequestEvent $event) {
if ($event
->isMainRequest()) {
$this
->setLanguageOverrides();
}
}
public function onContainerInitializeSubrequestFinished() {
$this
->setLanguageOverrides();
}
private function setLanguageOverrides() {
$this->negotiator
->setCurrentUser($this->currentUser);
if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
$this->languageManager
->setNegotiator($this->negotiator);
$this->languageManager
->setConfigOverrideLanguage($this->languageManager
->getCurrentLanguage());
}
$langcode = $this->languageManager
->getCurrentLanguage()
->getId();
$this->translation
->setDefaultLangcode($langcode);
}
public static function getSubscribedEvents() : array {
$events[KernelEvents::REQUEST][] = [
'onKernelRequestLanguage',
255,
];
$events[DrupalKernelInterface::CONTAINER_INITIALIZE_SUBREQUEST_FINISHED][] = [
'onContainerInitializeSubrequestFinished',
255,
];
return $events;
}
}