CurrentLocale.php 1.79 KB
Newer Older
1 2 3 4 5
<?php

namespace Drupal\commerce;

use Drupal\commerce\Resolver\ChainLocaleResolverInterface;
joshtaylor's avatar
joshtaylor committed
6
use Symfony\Component\HttpFoundation\RequestStack;
7 8 9 10 11 12 13 14 15 16 17 18

/**
 * Holds a reference to the current locale, resolved on demand.
 *
 * The ChainLocaleResolver runs the registered locale resolvers one by one until
 * one of them returns the locale.
 * The DefaultLocaleResolver runs last, and contains the default logic
 * which assembles the locale based on the current language and country.
 *
 * @see \Drupal\commerce\Resolver\ChainLocaleResolver
 * @see \Drupal\commerce\Resolver\DefaultLocaleResolver
 */
19
class CurrentLocale implements CurrentLocaleInterface {
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * The chain resolver.
   *
   * @var \Drupal\commerce\Resolver\ChainLocaleResolverInterface
   */
  protected $chainResolver;

  /**
   * Static cache of resolved locales. One per request.
   *
   * @var \SplObjectStorage
   */
  protected $locales;

  /**
43
   * Constructs a new CurrentLocale object.
44
   *
45
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
46
   *   The request stack.
47
   * @param \Drupal\commerce\Resolver\ChainLocaleResolverInterface $chain_resolver
48 49
   *   The chain resolver.
   */
50 51 52
  public function __construct(RequestStack $request_stack, ChainLocaleResolverInterface $chain_resolver) {
    $this->requestStack = $request_stack;
    $this->chainResolver = $chain_resolver;
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    $this->locales = new \SplObjectStorage();
  }

  /**
   * {@inheritdoc}
   */
  public function getLocale() {
    $request = $this->requestStack->getCurrentRequest();
    if (!$this->locales->contains($request)) {
      $this->locales[$request] = $this->chainResolver->resolve();
    }

    return $this->locales[$request];
  }

}