@@ -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;
7787use Psr\Container\ContainerInterface;
7888use 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+ */
8099class 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