Final Class Yiisoft\Yii\Middleware\Locale
| Inheritance | Yiisoft\Yii\Middleware\Locale |
|---|---|
| Implements | Psr\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
| 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
| 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
| 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 |
| $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 |
| $cookieDuration | DateInterval|null |
Locale cookie lifetime. |
| $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;
}
| 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);
}
Return new instance with changed cookie duration.
| public withCookieDuration( DateInterval|null $cookieDuration ): self | ||
| $cookieDuration | DateInterval|null |
Locale cookie lifetime. When set to |
public function withCookieDuration(?DateInterval $cookieDuration): self
{
$new = clone $this;
$new->cookieDuration = $cookieDuration;
return $new;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
Return new instance with supported locales specified.
| public withSupportedLocales( array $locales ): self | ||
| $locales | array |
List of supported locales in key-value format such as |
| throws | Yiisoft\Yii\Middleware\Exception\InvalidLocalesFormatException | |
|---|---|---|
public function withSupportedLocales(array $locales): self
{
$this->assertSupportedLocalesFormat($locales);
$new = clone $this;
$new->supportedLocales = $locales;
return $new;
}
Signup or Login in order to comment.