public function getUserLocale(Request $request)
    {
        $locales = $this->getAvailableLocales();
        $preferred = explode('_', $request->getPreferredLanguage());

        if ($request->attributes->get('_locale')) {
            $locale = $request->attributes->get('_locale');
        } elseif (($user = $this->getCurrentUser()) && $user->getLocale()) {
            $locale = $user->getLocale();
        } elseif ($request->getSession() && ($sessionLocale = $request->getSession()->get('_locale'))) {
            $locale = $sessionLocale;
        } elseif (count($preferred) > 0 && isset($locales[$preferred[0]])) {
            $locale = $preferred[0];
        } else {
            $locale = $this->defaultLocale;
        }

        if ($session = $request->getSession()) {
            $session->set('_locale', $locale);
        }

        return $locale;
    }