Skip to content
This repository was archived by the owner on Jan 29, 2020. It is now read-only.

Commit a95bc40

Browse files
authored
improve the "setting-locale w/o" cookbook example
- the current regex allows `/eng-us/`, I believe only `en`, `eng`, `en-us`, `en-US`, `en_us`, `en_US` (well, i would remove the last 2 as well) sould be allowed - the current regex requires a trailing `/` after the locale, we should allo base paths like `/en`, `/de` as well - the stripped part length is variable and should be computed from $locale (adding 1 for the root `/` char) - provide an example for using a default locale from app configuration
1 parent 934442f commit a95bc40

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

docs/book/v3/cookbook/setting-locale-without-routing-parameter.md

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,17 @@ class SetLocaleMiddleware implements MiddlewareInterface
4040
{
4141
private $helper;
4242

43-
public function __construct(UrlHelper $helper)
43+
private $defaultLocale;
44+
private $fallbackLocale = 'en_US';
45+
46+
const REGEX_LOCALE = '#^/(?P<locale>[a-z]{2,3}|[a-z]{2}[-_][a-zA-Z]{2})(?:/|$)#';
47+
48+
public function __construct(UrlHelper $helper, string $defaultLocale = null)
4449
{
4550
$this->helper = $helper;
51+
if ($defaultLocale) {
52+
$this->defaultLocale = $defaultLocale;
53+
}
4654
}
4755

4856
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
@@ -51,8 +59,8 @@ class SetLocaleMiddleware implements MiddlewareInterface
5159

5260
$path = $uri->getPath();
5361

54-
if (! preg_match('#^/(?P<locale>[a-z]{2,3}([-_][a-zA-Z]{2}|))/#', $path, $matches)) {
55-
Locale::setDefault('de_DE');
62+
if (! preg_match(self::REGEX_LOCALE, $path, $matches)) {
63+
Locale::setDefault($this->defaultLocale ?: $this->fallbackLocale);
5664
return $handler->handle($request);
5765
}
5866

@@ -61,7 +69,7 @@ class SetLocaleMiddleware implements MiddlewareInterface
6169
$this->helper->setBasePath($locale);
6270

6371
return $handler->handle($request->withUri(
64-
$uri->withPath(substr($path, 3))
72+
$uri->withPath(substr($path, strlen($locale) + 1))
6573
));
6674
}
6775
}
@@ -77,12 +85,24 @@ namespace App\I18n;
7785
use Psr\Container\ContainerInterface;
7886
use Zend\Expressive\Helper\UrlHelper;
7987

88+
/**
89+
* Configuration for setting a default locale should look like the following:
90+
*
91+
* <code>
92+
* 'i18n' => [
93+
* 'default_locale' => 'de_DE',
94+
* ]
95+
* </code>
96+
*/
8097
class SetLocaleMiddlewareFactory
8198
{
8299
public function __invoke(ContainerInterface $container)
83100
{
101+
$config = $container->get('config');
102+
84103
return new SetLocaleMiddleware(
85-
$container->get(UrlHelper::class)
104+
$container->get(UrlHelper::class),
105+
$config['i18n']['default_locale'] ?? null
86106
);
87107
}
88108
}

0 commit comments

Comments
 (0)