class LanguageNegotiationSession

Same name in other branches
  1. 9 core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSession
  2. 8.9.x core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSession
  3. 10 core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSession

Identify language from a request/session parameter.

Hierarchy

Expanded class hierarchy of LanguageNegotiationSession

1 file declares its use of LanguageNegotiationSession
LanguageUILanguageNegotiationTest.php in core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php

File

core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php, line 21

Namespace

Drupal\language\Plugin\LanguageNegotiation
View source
class LanguageNegotiationSession extends LanguageNegotiationMethodBase implements OutboundPathProcessorInterface, LanguageSwitcherInterface, ContainerFactoryPluginInterface {
    
    /**
     * Flag used to determine whether query rewriting is active.
     *
     * @var bool
     */
    protected $queryRewrite;
    
    /**
     * The query parameter name to rewrite.
     *
     * @var string
     */
    protected $queryParam;
    
    /**
     * The query parameter value to be set.
     *
     * @var string
     */
    protected $queryValue;
    
    /**
     * The request stack.
     *
     * @var \Symfony\Component\HttpFoundation\RequestStack
     */
    protected $requestStack;
    
    /**
     * The language negotiation method id.
     */
    const METHOD_ID = 'language-session';
    
    /**
     * Constructs a LanguageNegotiationSession object.
     *
     * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
     *   The request stack.
     */
    public function __construct(RequestStack $request_stack) {
        $this->requestStack = $request_stack;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
        return new static($container->get('request_stack'));
    }
    
    /**
     * {@inheritdoc}
     */
    public function getLangcode(?Request $request = NULL) {
        $config = $this->config
            ->get('language.negotiation')
            ->get('session');
        if (($param = $config['parameter']) && $request) {
            if ($request->query
                ->has($param)) {
                return $request->query
                    ->get($param);
            }
            if ($request->getSession()
                ->has($param)) {
                return $request->getSession()
                    ->get($param);
            }
        }
        return NULL;
    }
    
    /**
     * {@inheritdoc}
     */
    public function persist(LanguageInterface $language) {
        // We need to update the session parameter with the request value only if we
        // have an authenticated user.
        $langcode = $language->getId();
        if ($langcode && $this->languageManager) {
            $languages = $this->languageManager
                ->getLanguages();
            if ($this->currentUser
                ->isAuthenticated() && isset($languages[$langcode])) {
                $config = $this->config
                    ->get('language.negotiation')
                    ->get('session');
                $this->requestStack
                    ->getCurrentRequest()
                    ->getSession()
                    ->set($config['parameter'], $langcode);
            }
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function processOutbound($path, &$options = [], ?Request $request = NULL, ?BubbleableMetadata $bubbleable_metadata = NULL) {
        if ($request) {
            // The following values are not supposed to change during a single page
            // request processing.
            if (!isset($this->queryRewrite)) {
                if ($this->currentUser
                    ->isAnonymous()) {
                    $languages = $this->languageManager
                        ->getLanguages();
                    $config = $this->config
                        ->get('language.negotiation')
                        ->get('session');
                    $this->queryParam = $config['parameter'];
                    $this->queryValue = $request->query
                        ->has($this->queryParam) ? $request->query
                        ->get($this->queryParam) : NULL;
                    $this->queryRewrite = isset($languages[$this->queryValue]);
                }
                else {
                    $this->queryRewrite = FALSE;
                }
            }
            // If the user is anonymous, the user language negotiation method is
            // enabled, and the corresponding option has been set, we must preserve
            // any explicit user language preference even with cookies disabled.
            if ($this->queryRewrite) {
                if (!isset($options['query'][$this->queryParam])) {
                    $options['query'][$this->queryParam] = $this->queryValue;
                }
                if ($bubbleable_metadata) {
                    // Cached URLs that have been processed by this outbound path
                    // processor must be:
                    $bubbleable_metadata->addCacheTags($this->config
                        ->get('language.negotiation')
                        ->getCacheTags())
                        ->addCacheContexts([
                        'url.query_args:' . $this->queryParam,
                    ]);
                }
            }
        }
        return $path;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getLanguageSwitchLinks(Request $request, $type, Url $url) {
        $links = [];
        $query = [];
        parse_str($request->getQueryString() ?? '', $query);
        $config = $this->config
            ->get('language.negotiation')
            ->get('session');
        $param = $config['parameter'];
        $language_query = $request->getSession()
            ->has($param) ? $request->getSession()
            ->get($param) : $this->languageManager
            ->getCurrentLanguage($type)
            ->getId();
        foreach ($this->languageManager
            ->getNativeLanguages() as $language) {
            $langcode = $language->getId();
            $links[$langcode] = [
                // We need to clone the $url object to avoid using the same one for all
                // links. When the links are rendered, options are set on the $url
                // object, so if we use the same one, they would be set for all links.
'url' => clone $url,
                'title' => $language->getName(),
                'attributes' => [
                    'class' => [
                        'language-link',
                    ],
                ],
                'query' => $query,
            ];
            if ($language_query != $langcode) {
                $links[$langcode]['query'][$param] = $langcode;
            }
            else {
                $links[$langcode]['attributes']['class'][] = 'session-active';
            }
        }
        return $links;
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title
LanguageNegotiationMethodBase::$config protected property The configuration factory.
LanguageNegotiationMethodBase::$currentUser protected property The current active user.
LanguageNegotiationMethodBase::$languageManager protected property The language manager.
LanguageNegotiationMethodBase::setConfig public function Injects the configuration factory. Overrides LanguageNegotiationMethodInterface::setConfig
LanguageNegotiationMethodBase::setCurrentUser public function Injects the current user. Overrides LanguageNegotiationMethodInterface::setCurrentUser
LanguageNegotiationMethodBase::setLanguageManager public function Injects the language manager. Overrides LanguageNegotiationMethodInterface::setLanguageManager
LanguageNegotiationSession::$queryParam protected property The query parameter name to rewrite.
LanguageNegotiationSession::$queryRewrite protected property Flag used to determine whether query rewriting is active.
LanguageNegotiationSession::$queryValue protected property The query parameter value to be set.
LanguageNegotiationSession::$requestStack protected property The request stack.
LanguageNegotiationSession::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
LanguageNegotiationSession::getLangcode public function Performs language negotiation. Overrides LanguageNegotiationMethodInterface::getLangcode
LanguageNegotiationSession::getLanguageSwitchLinks public function Returns language switch links. Overrides LanguageSwitcherInterface::getLanguageSwitchLinks
LanguageNegotiationSession::METHOD_ID constant The language negotiation method id.
LanguageNegotiationSession::persist public function Notifies the plugin that the language code it returned has been accepted. Overrides LanguageNegotiationMethodBase::persist
LanguageNegotiationSession::processOutbound public function Processes the outbound path. Overrides OutboundPathProcessorInterface::processOutbound
LanguageNegotiationSession::__construct public function Constructs a LanguageNegotiationSession object.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.