alltube/classes/LocaleMiddleware.php

70 lines
1.9 KiB
PHP
Raw Normal View History

2017-05-29 19:11:59 +00:00
<?php
/**
* LocaleMiddleware class.
*/
2017-05-29 19:13:10 +00:00
2017-05-29 19:11:59 +00:00
namespace Alltube;
2017-05-30 20:20:16 +00:00
use Psr\Container\ContainerInterface;
2017-05-29 19:11:59 +00:00
use Slim\Http\Request;
use Slim\Http\Response;
use Teto\HTTP\AcceptLanguage;
/**
* Detect user locale.
*/
class LocaleMiddleware
{
/**
2017-05-30 20:20:16 +00:00
* LocaleMiddleware constructor.
2017-05-29 19:11:59 +00:00
*
2017-05-30 20:20:16 +00:00
* @param ContainerInterface $container Slim dependency container
2017-05-29 19:11:59 +00:00
*/
2017-05-30 20:20:16 +00:00
public function __construct(ContainerInterface $container)
{
$this->locale = $container->get('locale');
}
2017-05-29 19:11:59 +00:00
/**
* Test if a locale can be used for the current user.
*
* @param array $proposedLocale Locale array created by AcceptLanguage::parse()
*
* @return string Locale name if chosen, nothing otherwise
*/
public function testLocale(array $proposedLocale)
{
2017-05-30 20:20:16 +00:00
foreach ($this->locale->getSupportedLocales() as $locale => $name) {
2017-05-29 19:11:59 +00:00
$parsedLocale = AcceptLanguage::parse($locale);
if (isset($proposedLocale['language'])
&& $parsedLocale[1]['language'] == $proposedLocale['language']
&& $parsedLocale[1]['region'] == $proposedLocale['region']
) {
return $proposedLocale['language'].'_'.$proposedLocale['region'];
}
}
}
/**
2017-05-29 19:13:10 +00:00
* Main middleware function.
2017-05-29 19:11:59 +00:00
*
* @param Request $request PSR request
* @param Response $response PSR response
* @param callable $next Next middleware
*
* @return Response
*/
public function __invoke(Request $request, Response $response, callable $next)
{
$headers = $request->getHeader('Accept-Language');
2017-05-30 20:20:16 +00:00
$curLocale = $this->locale->getLocale();
if (!isset($curLocale)) {
$this->locale->setLocale(
AcceptLanguage::detect([$this, 'testLocale'], 'en_US', $headers[0])
);
}
2017-05-29 19:11:59 +00:00
return $next($request, $response);
}
}