src/Service/LocaleService.php line 80
<?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;class LocaleService{private $_requestStack;private $_localeSwitcher;private $_parameterBag;private $_translatableListener;public function __construct(RequestStack $requestStack,LocaleSwitcher $localeSwitcher,ParameterBag $parameterBag,TranslatableListener $translatableListener){$this->_requestStack = $requestStack;$this->_localeSwitcher = $localeSwitcher;$this->_parameterBag = $parameterBag;$this->_translatableListener = $translatableListener;}private static $_contentLocales;public function getAvailableLocales(){if (!self::$_contentLocales){$contentLocales = array();foreach($this->_parameterBag->get('content_locales') as $locale){$locale = strtolower(trim($locale));if ($locale != '' && strlen($locale) == 2)$contentLocales[] = $locale;}$defaultLocale = $this->getDefaultLocale();$locales = array();foreach($contentLocales as $locale){if ($locale == $defaultLocale)$locales = array_merge(array($locale), $locales);else$locales[] = $locale;}if (!$locales)throw new \Exception('No languages available.');self::$_contentLocales = $locales;}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);}public function getLocaleName($locale){$locales = Intl\Locales::getNames($this->getLocale());return isset($locales[$locale]) ? $locales[$locale] : '???';}}