Created
August 9, 2016 15:35
-
-
Save mcaskill/669e03cbffc1ab463c52ec2b30b116c0 to your computer and use it in GitHub Desktop.
Charcoal : Adding the Slim\Polyglot 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 | |
/** | |
* Application HTTP Middlewares | |
* | |
* @link https://github.com/mcaskill/Slim-Polyglot | |
* @global App $app The Charcoal application. | |
* @package Charcoal | |
*/ | |
use \Psr\Http\Message\ServerRequestInterface; | |
use \Psr\Http\Message\ResponseInterface; | |
// For managing translations from routes | |
use \McAskill\Slim\Polyglot\Polyglot; | |
use \Charcoal\App\App; | |
use \Charcoal\App\AppContainer; | |
use \Charcoal\App\Language\LanguageManager; | |
/** @var AppContainer $container The DI container used by the application. */ | |
$container = $app->getContainer(); | |
/** @var Language\LanguageManager The Charcoal application's language manager. */ | |
// $language_manager = $app->languageManager()->setup(); | |
$locales = $container['translator/locales']; | |
/** | |
* Enable Multilingual Routes | |
* | |
* Polyglot detects the current language from the request and selects an available language. | |
* That language is assigned to the Charcoal application's language manager. | |
* | |
* @see Polyglot For parsing languages in URIs | |
*/ | |
$app->add( | |
/** | |
* Invoke middleware | |
* | |
* @param RequestInterface $request PSR7 request object | |
* @param ResponseInterface $response PSR7 response object | |
* @param callable $next Next callable middleware | |
* | |
* @return ResponseInterface PSR7 response object | |
*/ | |
function (ServerRequestInterface $request, ResponseInterface $response, callable $next) use ($container, $locales) | |
{ | |
$uri = $request->getUri(); | |
$path = $uri->getPath(); | |
if (!preg_match('~^/admin\b~', $path)) { | |
$polyglot = new Polyglot([ | |
'languages' => $locales->languages(), | |
'fallbackLanguage' => $locales->defaultLanguage(), | |
'callbacks' => [ | |
[ $locales, 'setCurrentLanguage' ], | |
[ $container['translator/config'], 'setCurrentLanguage' ] | |
], | |
'regexPattern' => Polyglot::RFC1766, | |
'queryStringKeys' => [ 'lang', 'current_language', 'fb_locale' ], | |
'languageRequiredInUri' => false, | |
'languageIncludedInRoutes' => true, | |
]); | |
return $polyglot($request, $response, $next); | |
} | |
return $next($request, $response); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment