Skip to content

Instantly share code, notes, and snippets.

@RosanaRufer
Forked from carlcs/BusinessLogicVariable.php
Last active November 23, 2017 17:43
Show Gist options
  • Save RosanaRufer/fc1ef75f4d246b4b6b68c756194c5780 to your computer and use it in GitHub Desktop.
Save RosanaRufer/fc1ef75f4d246b4b6b68c756194c5780 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;
}
}
//
//{% set localeId = getCookie('locale') %}
//{% if not localeId %}
// {% set localeId = craft.businessLogic.getRequestedLocaleId() %} #}
// {{ setCookie('locale', 'de', now|date_modify('+1 years').timestamp,'/','rowa.de' ) }}
//{% endif %}
@RosanaRufer
Copy link
Author

    $browserLanguages = $this->getRequest()->getAcceptableLanguages();

    if (!empty($browserLanguages)) {
        $appLanguages = $this->getI18n()->getAppLocaleIds();

        foreach ($browserLanguages as $language) {
            if (in_array($language, $appLanguages, true)) {
                return $language;
            }
        }
    }

    return false;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment