src/Service/LocaleService.php line 93
<?phpnamespace App\Service;use Symfony\Component\HttpFoundation\RequestStack;use Symfony\Component\Translation\LocaleSwitcher;use Symfony\Component\Intl;use Gedmo\Translatable\TranslatableListener;use Psr\Container\ContainerInterface as ParameterBag;use App\Service\SettingsService;class LocaleService{private $_requestStack;private $_localeSwitcher;private $_parameterBag;private $_translatableListener;private $_settingsService;public function __construct(RequestStack $requestStack,LocaleSwitcher $localeSwitcher,ParameterBag $parameterBag,TranslatableListener $translatableListener,SettingsService $settingsService){$this->_requestStack = $requestStack;$this->_localeSwitcher = $localeSwitcher;$this->_parameterBag = $parameterBag;$this->_translatableListener = $translatableListener;$this->_settingsService = $settingsService;}private static $_contentLocales;public function getAvailableLocales(){if (!self::$_contentLocales){self::$_contentLocales = array();$langs = $this->_settingsService->getValue(SettingsService::APP_ADDITIONAL_LANGS, false);if ($langs != ''){$langs = json_decode($langs, true);if ($langs)self::$_contentLocales = $langs;}$defaultContentLocale = $this->_parameterBag->get('default_content_locale');if ($defaultContentLocale == '')throw new \Exception('No default language is set.');self::$_contentLocales = array_unique(array_merge([$defaultContentLocale], self::$_contentLocales));}return self::$_contentLocales;}public function getDefaultLocale(){$locale = $this->_parameterBag->get('default_locale');if ($locale == '')throw new \Exception('No default language is set.');return $locale;}public function getLocale(){$request = $this->_requestStack->getCurrentRequest();return $request->getSession()->get('_locale', $request->getLocale());}public function setLocale($locale){$availableLocales = $this->getAvailableLocales();if (!in_array($locale, $availableLocales)){$locale = $this->getDefaultLocale();if (!in_array($locale, $availableLocales))throw new \Exception('Default language does not exist.');}$request = $this->_requestStack->getCurrentRequest();$request->getSession()->set('_locale', $locale);$request->setLocale($locale);$this->_translatableListener->setTranslatableLocale($locale);$this->_localeSwitcher->setLocale($locale);}private static $_localeNames = array();public function getLocaleName($locale){$_locale = $this->getLocale();if (!isset(self::$_localeNames[$_locale]))self::$_localeNames[$_locale] = Intl\Locales::getNames($_locale);return isset(self::$_localeNames[$_locale][$locale]) ? self::$_localeNames[$_locale][$locale] : '???';}}