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

Commit 28432b5

Browse files
committed
Merge branch 'hotfix/633'
Close #633
2 parents 2c4d4e2 + d8921eb commit 28432b5

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

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

Lines changed: 27 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,17 +59,19 @@ 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

5967
$locale = $matches['locale'];
6068
Locale::setDefault(Locale::canonicalize($locale));
6169
$this->helper->setBasePath($locale);
6270

71+
$path = substr($path, strlen($locale) + 1);
72+
6373
return $handler->handle($request->withUri(
64-
$uri->withPath(substr($path, 3))
74+
$uri->withPath($path ?: '/')
6575
));
6676
}
6777
}
@@ -77,12 +87,24 @@ namespace App\I18n;
7787
use Psr\Container\ContainerInterface;
7888
use Zend\Expressive\Helper\UrlHelper;
7989

90+
/**
91+
* Configuration for setting a default locale should look like the following:
92+
*
93+
* <code>
94+
* 'i18n' => [
95+
* 'default_locale' => 'de_DE',
96+
* ]
97+
* </code>
98+
*/
8099
class SetLocaleMiddlewareFactory
81100
{
82101
public function __invoke(ContainerInterface $container)
83102
{
103+
$config = $container->has('config') ? $container->get('config') : [];
104+
84105
return new SetLocaleMiddleware(
85-
$container->get(UrlHelper::class)
106+
$container->get(UrlHelper::class),
107+
$config['i18n']['default_locale'] ?? null
86108
);
87109
}
88110
}

0 commit comments

Comments
 (0)