Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save peterlafferty/181235899e824261a730f173ae402653 to your computer and use it in GitHub Desktop.
Save peterlafferty/181235899e824261a730f173ae402653 to your computer and use it in GitHub Desktop.
example silex app for custom parsing of accept-header and matching it to a locale
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\AcceptHeader;
$app = new Silex\Application();
$app->before(function (Request $request) use ($app) {
$languages = ['en', 'pt_BR', 'ja', 'zh', 'zh_Hans'];
$locale = getPrefferedLanguage(
$languages,
$request->headers->get('Accept-Language')
);
$app['locale'] = $locale;
$app['contentLanguage'] = str_replace('_', '-', $locale);
});
$app->after(function (Request $request, Response $response) use ($app) {
$response->headers->set('Content-Language', $app['contentLanguage']);
});
$app->get('/', function () use ($app) {
return new JsonResponse(
[
'locale' => $app['locale'],
'contentLanguage' => $app['contentLanguage']
]
);
});
$app->run();
function getPrefferedLanguage($locales, $acceptLanguageHeader)
{
$acceptLanguages = array_keys(
AcceptHeader::fromString(
$acceptLanguageHeader
)->all()
);
foreach ($acceptLanguages as $languageTag) {
$subtags = explode('-', $languageTag);
do {
$tag = implode('_', $subtags);
if (in_array($tag, $locales)) {
return $tag;
}
array_pop($subtags);
} while (count($subtags) > 0);
}
return $locales[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment