You are here

public function LanguageCookieSubscriber::setLanguageCookie in Language Cookie 8

Event callback for setting the language cookie.

Parameters

\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event: The response event.

Return value

bool

  • FALSE if a condition plugin prevented the cookie from being set.
  • TRUE if all conditions pass. If a language is available, the cookie will have been set.

File

src/EventSubscriber/LanguageCookieSubscriber.php, line 156

Class

LanguageCookieSubscriber
Provides a LanguageCookieSubscriber.

Namespace

Drupal\language_cookie\EventSubscriber

Code

public function setLanguageCookie(FilterResponseEvent $event) {
  $this->event = $event;
  $config = $this->configFactory
    ->get('language_cookie.negotiation');
  $manager = $this->languageCookieConditionManager;

  // Get the current language to set in the cookie to by running through all
  // language negotiation methods with higher priority (in terms of weight)
  // than the Language Cookie method.
  $language = $this
    ->getLanguage();
  if (!$language instanceof LanguageInterface) {
    return FALSE;
  }

  // Run through the condition plugins that may prevent a cookie from being
  // set.
  foreach ($manager
    ->getDefinitions() as $def) {

    /** @var \Drupal\language_cookie\LanguageCookieConditionInterface $condition_plugin */
    $condition_plugin = $manager
      ->createInstance($def['id'], $config
      ->get());
    $condition_plugin
      ->setCurrentLanguage($language);
    if (!$manager
      ->execute($condition_plugin)) {
      return FALSE;
    }
  }
  $request = $this->event
    ->getRequest();

  // Get the name of the cookie parameter.
  $param = $config
    ->get('param');
  if (!$request->cookies
    ->has($param) || $request->cookies
    ->get($param) != $language
    ->getId() || $config
    ->get('set_on_every_pageload')) {
    $cookie = new Cookie($param, $language
      ->getId(), $this->time
      ->getRequestTime() + $config
      ->get('time'), $config
      ->get('path'), $config
      ->get('domain'), $config
      ->get('secure'), $config
      ->get('http_only'));

    // Allow other modules to change the $cookie.
    $this->moduleHandler
      ->alter('language_cookie', $cookie);
    $this->event
      ->getResponse()->headers
      ->setCookie($cookie);
  }
  return TRUE;
}