Skip to content

Instantly share code, notes, and snippets.

@carlcs
Created November 17, 2017 15:19
Show Gist options
  • Save carlcs/01642fc880ebbe6450e32137de2115d0 to your computer and use it in GitHub Desktop.
Save carlcs/01642fc880ebbe6450e32137de2115d0 to your computer and use it in GitHub Desktop.
<?php
namespace Craft;
class BusinessLogicVariable
{
public function getRequestedLocaleId()
{
// Return the current locale ID if any path is requested
if (craft()->request->getUrl() !== '/') {
return craft()->locale->id;
}
// Get the browser's preferred languages
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && preg_match_all('/([\w\-_]+)\s*(?:;\s*q\s*=\s*(\d*\.\d*))?/', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches, PREG_SET_ORDER)) {
$languages = array();
$weights = array();
foreach ($matches as $match) {
$languages[] = strtolower(substr($match[1], 0, 2));
$weights[] = !empty($match[2]) ? floatval($match[2]) : 1;
}
// Sort the languages by their weight
array_multisort($weights, SORT_NUMERIC, SORT_DESC, $languages);
// Find the first with corresponding locale
foreach ($languages as $language) {
if (array_search($language, craft()->i18n->getSiteLocaleIds()) !== false) {
$matchingLocale = $language;
break;
}
}
}
// Default to German
if (!isset($matchingLocale)) {
$matchingLocale = 'de';
}
return $matchingLocale;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment