-
-
Save juriansluiman/3090332 to your computer and use it in GitHub Desktop.
| <?php | |
| namespace Application; | |
| use Locale; | |
| use Zend\EventManager\Event; | |
| use Zend\ModuleManager\Feature; | |
| class Module implements | |
| Feature\BootstrapListenerInterface | |
| { | |
| public function onBootstrap(Event $e) | |
| { | |
| $default = 'nl'; | |
| $supported = array('en', 'en-GB'); | |
| $app = $e->getApplication(); | |
| $headers = $app->getRequest()->getHeaders(); | |
| if ($headers->has('Accept-Language')) { | |
| $locales = $headers->get('Accept-Language')->getPrioritized(); | |
| // Loop through all locales, highest priority first | |
| foreach ($locales as $locale) { | |
| if (!!($match = Locale::lookup($supported, $locale))) { | |
| // The locale is one of our supported list | |
| Locale::setDefault($match); | |
| break; | |
| } | |
| } | |
| if (!$match) { | |
| // Nothing from the supported list is a match | |
| Locale::setDefault($default); | |
| } | |
| } else { | |
| Locale::setDefault($default); | |
| } | |
| } | |
| } |
@abrahaj: what do you mean? "Locale" is the ext/intl php extension. So you need to have that extension installed. You have a bit more surrounding text about this on my blog: http://juriansluiman.nl/en/article/118/auto-detect-user-locale-with-zend-http-request-headers-and-ext-intl
Apologize, I was not aware of that bit of information!
Regards
Stumbled onto this, thanks. Had to make a slight revision to make it work.
$locales = $headers->get('Accept-Language')->getPrioritized();
/** @var LanguageFieldValuePart $locale */
foreach ($locales as $locale){
if( !!($match = Locale::lookup($other_locales, $locale->getTypeString() )) )Thanks very much vor this snippet, which has worked for us very well until now. Unfortunately, recently we discovered a bug.
Think of the following:
$default = 'de_DE';
$supported = array('de_DE', 'en-GB');The system also includes language files for exactly those locales.
Now, along comes a visitor:
Accept-Language: de,en-US;q=0.7,en;q=0.3`
Theory: He would get to see a German application.
Fact: He gets the English version.
We need to extend the snippet to also include sublocales or related locales (de_AT etc.) in its search. Currently working on that.
Please put a reference to Locale.php as well :)