0 follower

Final Class Yiisoft\Yii\Middleware\Locale

InheritanceYiisoft\Yii\Middleware\Locale
ImplementsPsr\Http\Server\MiddlewareInterface

Locale middleware supports locale-based routing and configures URL generator. With Yiisoft\Yii\Middleware\Event\SetLocaleEvent it's also possible to configure locale in other services such as translator or session.

You should place it before Route middleware in the middleware list.

Public Methods

Hide inherited methods

Method Description Defined By
__construct() Yiisoft\Yii\Middleware\Locale
process() Yiisoft\Yii\Middleware\Locale
withCookieDuration() Return new instance with changed cookie duration. Yiisoft\Yii\Middleware\Locale
withCookieName() Return new instance with the name of cookie parameter to store found locale. Effective only when $cookieDuration isn't null. Yiisoft\Yii\Middleware\Locale
withDefaultLocale() Return new instance with default locale specified. Yiisoft\Yii\Middleware\Locale
withDetectLocale() Return new instance with enabled or disabled detection of locale based on Accept-Language header. Yiisoft\Yii\Middleware\Locale
withIgnoredRequestUrlPatterns() Return new instance with WildcardPattern patterns for ignoring requests with URLs matching. Yiisoft\Yii\Middleware\Locale
withQueryParameterName() Return new instance with the name of the query string parameter to look for locale. Yiisoft\Yii\Middleware\Locale
withSecureCookie() Return new instance with enabled or disabled secure cookies. Yiisoft\Yii\Middleware\Locale
withSupportedLocales() Return new instance with supported locales specified. Yiisoft\Yii\Middleware\Locale

Constants

Hide inherited constants

Constant Value Description Defined By
DEFAULT_LOCALE 'en' Yiisoft\Yii\Middleware\Locale
DEFAULT_LOCALE_NAME '_language' Yiisoft\Yii\Middleware\Locale
LOCALE_SEPARATORS [ '-', '_', ] Yiisoft\Yii\Middleware\Locale

Method Details

Hide inherited methods

__construct() public method

public __construct( \Psr\EventDispatcher\EventDispatcherInterface $eventDispatcher, \Yiisoft\Router\UrlGeneratorInterface $urlGenerator, \Psr\Log\LoggerInterface $logger, \Psr\Http\Message\ResponseFactoryInterface $responseFactory, array $supportedLocales = [], string[] $ignoredRequestUrlPatterns = [], boolean $secureCookie false, DateInterval|null $cookieDuration null, \Psr\Clock\ClockInterface|null $clock null ): mixed
$eventDispatcher \Psr\EventDispatcher\EventDispatcherInterface

Event dispatcher instance to dispatch events.

$urlGenerator \Yiisoft\Router\UrlGeneratorInterface

URL generator instance to set locale for.

$logger \Psr\Log\LoggerInterface

Logger instance to write debug logs to.

$responseFactory \Psr\Http\Message\ResponseFactoryInterface

Response factory used to create redirect responses.

$supportedLocales array

List of supported locales in key-value format such as ['ru' => 'ru_RU', 'uz' => 'uz_UZ'].

$ignoredRequestUrlPatterns string[]

\Yiisoft\Strings\WildcardPattern Patterns for ignoring requests with URLs matching.

$secureCookie boolean

Whether middleware should flag locale cookie as secure. Effective only when $cookieDuration isn't null.

$cookieDuration DateInterval|null

Locale cookie lifetime. null disables saving locale to cookies completely.

$clock \Psr\Clock\ClockInterface|null

                public function __construct(
    private EventDispatcherInterface $eventDispatcher,
    private UrlGeneratorInterface $urlGenerator,
    private LoggerInterface $logger,
    private ResponseFactoryInterface $responseFactory,
    array $supportedLocales = [],
    private array $ignoredRequestUrlPatterns = [],
    private bool $secureCookie = false,
    private ?DateInterval $cookieDuration = null,
    private ?ClockInterface $clock = null,
) {
    $this->assertSupportedLocalesFormat($supportedLocales);
    $this->supportedLocales = $supportedLocales;
}

            
process() public method

public process( \Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Server\RequestHandlerInterface $handler ): \Psr\Http\Message\ResponseInterface
$request \Psr\Http\Message\ServerRequestInterface
$handler \Psr\Http\Server\RequestHandlerInterface

                public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
    if (empty($this->supportedLocales) || $this->isRequestIgnored($request)) {
        return $handler->handle($request);
    }
    $uri = $request->getUri();
    $path = $uri->getPath();
    $query = $uri->getQuery();
    $locale = $this->getLocaleFromPath($path);
    if ($locale !== null) {
        if ($locale === $this->defaultLocale && $request->getMethod() === Method::GET) {
            return $this->saveLocale(
                $locale,
                $this->createRedirectResponse(substr($path, strlen($locale) + 1) ?: '/', $query)
            );
        }
    } else {
        /** @psalm-var array<string, string> $queryParameters */
        $queryParameters = $request->getQueryParams();
        $locale = $this->getLocaleFromQuery($queryParameters);
        if ($locale === null && $this->cookieDuration !== null) {
            /** @psalm-var array<string, string> $cookieParameters */
            $cookieParameters = $request->getCookieParams();
            $locale = $this->getLocaleFromCookies($cookieParameters);
        }
        if ($locale === null && $this->detectLocale) {
            $locale = $this->detectLocale($request);
        }
        if ($locale === null || $locale === $this->defaultLocale) {
            $this->urlGenerator->setDefaultArgument($this->queryParameterName, null);
            $request = $request->withUri($uri->withPath('/' . $this->defaultLocale . $path));
            return $handler->handle($request);
        }
        if ($request->getMethod() === Method::GET) {
            return $this->createRedirectResponse('/' . $locale . $path, $query);
        }
    }
    /** @var string $locale */
    $this->eventDispatcher->dispatch(new SetLocaleEvent($this->supportedLocales[$locale]));
    $this->urlGenerator->setDefaultArgument($this->queryParameterName, $locale);
    $response = $handler->handle($request);
    return $this->saveLocale($locale, $response);
}

            
withCookieDuration() public method

Return new instance with changed cookie duration.

public withCookieDuration( DateInterval|null $cookieDuration ): self
$cookieDuration DateInterval|null

Locale cookie lifetime. When set to null, saving locale to cookies is disabled completely.

                public function withCookieDuration(?DateInterval $cookieDuration): self
{
    $new = clone $this;
    $new->cookieDuration = $cookieDuration;
    return $new;
}

            
withCookieName() public method

Return new instance with the name of cookie parameter to store found locale. Effective only when $cookieDuration isn't null.

public withCookieName( string $cookieName ): self
$cookieName string

Name of cookie parameter.

                public function withCookieName(string $cookieName): self
{
    $new = clone $this;
    $new->cookieName = $cookieName;
    return $new;
}

            
withDefaultLocale() public method

Return new instance with default locale specified.

public withDefaultLocale( string $defaultLocale ): self
$defaultLocale string

Default locale. It must be present as a key in $supportedLocales.

                public function withDefaultLocale(string $defaultLocale): self
{
    if (!array_key_exists($defaultLocale, $this->supportedLocales)) {
        throw new InvalidArgumentException('Default locale allows only keys from supported locales.');
    }
    $new = clone $this;
    $new->defaultLocale = $defaultLocale;
    return $new;
}

            
withDetectLocale() public method

Return new instance with enabled or disabled detection of locale based on Accept-Language header.

public withDetectLocale( boolean $enabled ): self
$enabled boolean

Whether middleware should detect locale.

                public function withDetectLocale(bool $enabled): self
{
    $new = clone $this;
    $new->detectLocale = $enabled;
    return $new;
}

            
withIgnoredRequestUrlPatterns() public method

Return new instance with WildcardPattern patterns for ignoring requests with URLs matching.

public withIgnoredRequestUrlPatterns( string[] $patterns ): self
$patterns string[]

Patterns.

                public function withIgnoredRequestUrlPatterns(array $patterns): self
{
    $new = clone $this;
    $new->ignoredRequestUrlPatterns = $patterns;
    return $new;
}

            
withQueryParameterName() public method

Return new instance with the name of the query string parameter to look for locale.

public withQueryParameterName( string $queryParameterName ): self
$queryParameterName string

Name of the query string parameter.

                public function withQueryParameterName(string $queryParameterName): self
{
    $new = clone $this;
    $new->queryParameterName = $queryParameterName;
    return $new;
}

            
withSecureCookie() public method

Return new instance with enabled or disabled secure cookies.

public withSecureCookie( boolean $secure ): self
$secure boolean

Whether middleware should flag locale cookie as secure.

                public function withSecureCookie(bool $secure): self
{
    $new = clone $this;
    $new->secureCookie = $secure;
    return $new;
}

            
withSupportedLocales() public method

Return new instance with supported locales specified.

public withSupportedLocales( array $locales ): self
$locales array

List of supported locales in key-value format such as ['ru' => 'ru_RU', 'uz' => 'uz_UZ'].

throws Yiisoft\Yii\Middleware\Exception\InvalidLocalesFormatException

                public function withSupportedLocales(array $locales): self
{
    $this->assertSupportedLocalesFormat($locales);
    $new = clone $this;
    $new->supportedLocales = $locales;
    return $new;
}