пример
final class Locale implements MiddlewareInterface
{
public const ATTRIBUTE_NAME = 'locale';
private Parameters $parameters;
private I18n\TranslatorInterface $translator;
public function __construct(Parameters $params, I18n\TranslatorInterface $translator)
{
$this->parameters = $params;
$this->translator = $translator;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$availableLocales = $this->parameters->get('locale.available', []);
foreach ($this->fetchLocales($request) as $localeString) {
if (in_array($localeString, $availableLocales, true)) {
$locale = new I18n\Locale($localeString);
break;
}
}
$locale = $locale ?? new I18n\Locale((string)$this->parameters->get('locale.fallback'));
$this->translator->setLocale($locale->asString());
return $handler->handle($request->withAttribute(self::ATTRIBUTE_NAME, $locale));
}
/**
*
@param ServerRequestInterface $request
*
@return \Generator
*/
public function fetchLocales(ServerRequestInterface $request): \Generator
{
$header = $request->getHeaderLine('Accept-Language');
foreach (explode(',', $header) as $value) {
if (strpos($value, ';') !== false) {
yield substr($value, 0, strpos($value, ';'));
}
yield $value;
}
}
}