Skip to content

Instantly share code, notes, and snippets.

@argentinaluiz
Created December 15, 2016 19:26
Show Gist options
  • Save argentinaluiz/8ce9e628f0ceb3b633d2abc0ae6a922d to your computer and use it in GitHub Desktop.
Save argentinaluiz/8ce9e628f0ceb3b633d2abc0ae6a922d to your computer and use it in GitHub Desktop.
Change locale in Zend Expressive by query params and middleware
<?php
namespace CodeEmailMKT\Application\Middleware;
use Locale;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Expressive\Helper\UrlHelper;
class SetLocaleMiddleware
{
private $helper;
public function __construct(UrlHelper $helper)
{
$this->helper = $helper;
}
public function __invoke(ServerRequestInterface $request, $response, callable $next)
{
$queryParams = $request->getQueryParams();
$locale = $queryParams['locale'] ?? '';
if (!preg_match('/(?P<locale>[a-z]{2,3}([-_][a-zA-Z]{2}|))/', $locale, $matches)) {
Locale::setDefault('de_DE');
return $next($request, $response);
}
$locale = $matches['locale'];
Locale::setDefault(Locale::canonicalize($locale));
$this->helper->setBasePath($locale);
return $next(
$request,
$response
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment