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 {@see 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
{@see $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 {@see 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 mixed __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 $cookieDuration = null, ?\Psr\Clock\ClockInterface $clock = null ) | ||
| $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[] |
{@see \Yiisoft\Strings\WildcardPattern Patterns} for ignoring requests with URLs matching. |
| $secureCookie | boolean |
Whether middleware should flag locale cookie as secure. Effective only when
{@see $cookieDuration} isn't |
| $cookieDuration | ?\DateInterval |
Locale cookie lifetime. |
| $clock | ?\Psr\Clock\ClockInterface | |
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 \Psr\Http\Message\ResponseInterface process ( \Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Server\RequestHandlerInterface $handler ) | ||
| $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 self withCookieDuration ( ?\DateInterval $cookieDuration ) | ||
| $cookieDuration | ?\DateInterval |
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
{@see $cookieDuration} isn't null.
| public self withCookieName ( string $cookieName ) | ||
| $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 self withDefaultLocale ( string $defaultLocale ) | ||
| $defaultLocale | string |
Default locale. It must be present as a key in {@see $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 self withDetectLocale ( boolean $enabled ) | ||
| $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 {@see WildcardPattern patterns} for ignoring requests with URLs matching.
| public self withIgnoredRequestUrlPatterns ( string[] $patterns ) | ||
| $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 self withQueryParameterName ( string $queryParameterName ) | ||
| $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 self withSecureCookie ( boolean $secure ) | ||
| $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 self withSupportedLocales ( array $locales ) | ||
| $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.