Created
December 15, 2016 19:26
-
-
Save argentinaluiz/8ce9e628f0ceb3b633d2abc0ae6a922d to your computer and use it in GitHub Desktop.
Change locale in Zend Expressive by query params and middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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