Exemplo n.º 1
0
    /**
     * {@inheritdoc}
     */
    public function validate($value, Constraint $constraint)
    {
        if (!$constraint instanceof Locale) {
            throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Locale');
        }

        if (null === $value || '' === $value) {
            return;
        }

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $value = (string) $value;
        $locales = Intl::getLocaleBundle()->getLocaleNames();

        if (!isset($locales[$value])) {
            if ($this->context instanceof ExecutionContextInterface) {
                $this->context->buildViolation($constraint->message)
                    ->setParameter('{{ value }}', $this->formatValue($value))
                    ->setCode(Locale::NO_SUCH_LOCALE_ERROR)
                    ->addViolation();
            } else {
                $this->buildViolation($constraint->message)
                    ->setParameter('{{ value }}', $this->formatValue($value))
                    ->setCode(Locale::NO_SUCH_LOCALE_ERROR)
                    ->addViolation();
            }
        }
    }
Exemplo n.º 2
0
 /**
  * @return string
  */
 public function getName($locale = null)
 {
     $enc = 'utf-8';
     $names = Intl::getLocaleBundle()->getLocaleNames($locale ?: $this->locale);
     $str = isset($names[$this->locale]) ? $names[$this->locale] : $this->locale;
     return mb_strtoupper(mb_substr($str, 0, 1, $enc), $enc) . mb_substr($str, 1, mb_strlen($str, $enc), $enc);
 }
Exemplo n.º 3
0
 /**
  * {@inheritdoc}
  */
 public function configureOptions(OptionsResolver $resolver)
 {
     $resolver->setDefaults(array(
         'choices' => Intl::getLocaleBundle()->getLocaleNames(),
         'choice_translation_domain' => false,
     ));
 }
Exemplo n.º 4
0
 /**
  * @param mixed $value
  *
  * @throws InvalidLocaleException
  */
 protected function guard($value)
 {
     $localeName = Intl::getLocaleBundle()->getLocaleName($value);
     if (null === $localeName) {
         throw new InvalidLocaleException($value);
     }
 }
Exemplo n.º 5
0
 /**
  * {@inheritdoc}
  */
 public function loadChoiceList($value = null)
 {
     if (null !== $this->choiceList) {
         return $this->choiceList;
     }
     return $this->choiceList = new ArrayChoiceList(array_flip(Intl::getLocaleBundle()->getLocaleNames()), $value);
 }
 /**
  * Display the name of a locale by its code, like English (United States) when you provide en_US
  *
  * @param string $code
  *
  * @return string
  */
 public function prettyLocaleName($code)
 {
     if (empty($code)) {
         return '';
     }
     return Intl::getLocaleBundle()->getLocaleName($code);
 }
Exemplo n.º 7
0
 public function getGlobals()
 {
     $locales = array('current' => null, 'other' => null);
     $enabledLocales = $this->localeRepository->findBy(array('isEnabled' => true));
     $otherLocales = $enabledLocales;
     if (count($enabledLocales)) {
         /** @var Locale $locale */
         foreach ($enabledLocales as $localeKey => $locale) {
             if ($this->currentLocale == $locale->getCode()) {
                 $locales['current'] = $locale;
                 unset($otherLocales[$localeKey]);
                 break;
             }
         }
     }
     if (!count($enabledLocales) || empty($locales['current'])) {
         $defaultLocaleCode = $this->container->getParameter('locale');
         $locale = new Locale();
         $locale->setCode($defaultLocaleCode);
         $locale->setTitle(Intl::getLocaleBundle()->getLocaleName($defaultLocaleCode, $defaultLocaleCode));
         $locales['current'] = $locale;
     }
     $locales['other'] = $otherLocales;
     return array('locales' => $locales);
 }
Exemplo n.º 8
0
 /**
  * @return array
  */
 public function getLocales()
 {
     $localeCodes = explode('|', $this->locales);
     foreach ($localeCodes as $localeCode) {
         $locales[] = array('code' => $localeCode, 'name' => Intl::getLocaleBundle()->getLocaleName($localeCode, $localeCode));
     }
     return $locales;
 }
Exemplo n.º 9
0
 /**
  * Builds frontend locale menu.
  *
  * @return ItemInterface
  */
 public function createMenu()
 {
     $menu = $this->factory->createItem('root', array('childrenAttributes' => array('class' => 'nav nav-pills')));
     foreach ($this->localeProvider->getAvailableLocales() as $locale) {
         $code = $locale->getCode();
         $menu->addChild($code, array('route' => 'sylius_locale_change', 'routeParameters' => array('locale' => $code)))->setLabel(Intl::getLocaleBundle()->getLocaleName($code));
     }
     return $menu;
 }
Exemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public function getLocaleNames()
 {
     $locales = Intl::getLocaleBundle()->getLocaleNames();
     $Data = [];
     foreach ($locales as $locale => $name) {
         $Data[$locale] = sprintf('%s (%s)', $name, $locale);
     }
     return $Data;
 }
Exemplo n.º 11
0
 /**
  * @param ObjectManager $manager
  */
 public function load(ObjectManager $manager)
 {
     $localeSettings = $this->container->get('oro_locale.settings');
     $locale = new Locale();
     $locale->setCode(Intl::getLocaleBundle()->getLocaleName($localeSettings->getLanguage(), $localeSettings->getLocale()));
     $manager->persist($locale);
     /** @var EntityManager $manager */
     $manager->flush($locale);
     $this->addReference('default_website_locale', $locale);
 }
Exemplo n.º 12
0
 /**
  * Should be private, used public to support PHP 5.3
  *
  * @internal
  *
  * @return array
  */
 public function getAvailableLocales()
 {
     $availableLocales = Intl::getLocaleBundle()->getLocaleNames();
     /** @var LocaleInterface[] $definedLocales */
     $definedLocales = $this->localeRepository->findAll();
     foreach ($definedLocales as $locale) {
         unset($availableLocales[$locale->getCode()]);
     }
     return $availableLocales;
 }
Exemplo n.º 13
0
 protected function beforeRender()
 {
     parent::beforeRender();
     $this->template->parameters = $this->context->parameters;
     $this->template->acl = $this->acl;
     $this->template->addFilter('langName', function ($locale) {
         return Intl::getLocaleBundle()->getLocaleName($locale);
     });
     $this->template->projects = $this->projectFacade->findAll();
 }
Exemplo n.º 14
0
 /**
  * {@inheritdoc}
  */
 protected function doLoad(ObjectManager $manager)
 {
     $defaultCode = $this->getContainer()->getParameter('lug.locale');
     foreach (array_keys(Intl::getLocaleBundle()->getLocaleNames()) as $code) {
         $locale = $this->getFactory()->create(['code' => $code, 'enabled' => $code === $defaultCode, 'required' => $code === $defaultCode]);
         $manager->persist($locale);
         $this->setReference('lug.locale.' . $code, $locale);
     }
     $manager->flush();
 }
Exemplo n.º 15
0
 /**
  * @return array
  */
 protected function getLanguageChoices()
 {
     // ensure that default value is always in choice list
     $defaultValue = $this->cm->get(self::CONFIG_KEY, true);
     $availableTranslations = (array) $this->cm->get(TranslationStatusInterface::CONFIG_KEY);
     $availableTranslations = array_filter($availableTranslations, function ($languageStatus) {
         return $languageStatus === TranslationStatusInterface::STATUS_ENABLED;
     });
     $availableLanguages = array_merge(array_keys($availableTranslations), [$defaultValue]);
     $allLanguages = Intl::getLocaleBundle()->getLocaleNames('en');
     return array_intersect_key($allLanguages, array_flip($availableLanguages));
 }
 /**
  * {@inheritdoc}
  */
 public function localeNameFilter($locale, $displayLocale = null)
 {
     $localeBundle = Intl::getLocaleBundle();
     if ($localeBundle instanceof LocaleDataProvider) {
         $aliases = $localeBundle->getAliases();
         if (isset($aliases[$displayLocale])) {
             $displayLocale = $aliases[$displayLocale];
         }
     }
     $localeName = Intl::getLocaleBundle()->getLocaleName($locale, $displayLocale);
     return $localeName;
 }
Exemplo n.º 17
0
 /**
  * @param FormBuilderInterface $builder
  * @param array $options
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     if (!empty($this->localeRepository)) {
         $locales = Intl::getLocaleBundle()->getLocaleNames();
         $existingLocales = $this->localeRepository->findAll();
         /** @var Locale $existingLocale */
         foreach ($existingLocales as $existingLocale) {
             unset($locales[$existingLocale->getCode()]);
         }
         $builder->add('code', 'choice', array('choices' => $locales, 'attr' => array('class' => 'chosen')));
     }
     $builder->add('isEnabled', 'checkbox', array('required' => false, 'attr' => array('class' => 'switchery')))->add('isFallback', 'checkbox', array('required' => false, 'attr' => array('class' => 'switchery')));
 }
Exemplo n.º 18
0
 /**
  * Get the list of available locales for the PIM.
  *
  * @return array
  */
 public function getLocales()
 {
     $locales = [];
     $fallbackLocales = $this->translator->getFallbackLocales();
     $localeNames = Intl::getLocaleBundle()->getLocaleNames(self::MAIN_LOCALE);
     $mainProgress = $this->getProgress(self::MAIN_LOCALE);
     foreach ($localeNames as $code => $locale) {
         if ($this->isAvailableLocale($fallbackLocales, $locales, $code, $mainProgress)) {
             $locales[$code] = $locale;
         }
     }
     return $locales;
 }
Exemplo n.º 19
0
 /**
  * Builds frontend locale menu.
  *
  * @return ItemInterface
  */
 public function createMenu()
 {
     $locales = $this->localeProvider->getAvailableLocalesCodes();
     $menu = $this->factory->createItem('root', ['childrenAttributes' => ['class' => 'nav nav-pills']]);
     if (1 === count($locales)) {
         $menu->setDisplay(false);
         return $menu;
     }
     foreach ($locales as $locale) {
         $menu->addChild($locale, ['route' => 'sylius_locale_change', 'routeParameters' => ['locale' => $locale]])->setLabel(Intl::getLocaleBundle()->getLocaleName($locale));
     }
     return $menu;
 }
Exemplo n.º 20
0
 /**
  * @Route("/available-translations", name="oro_translation_available_translations")
  * @Template
  */
 public function availableTranslationsAction()
 {
     $statisticProvider = $this->get('oro_translation.statistic_provider');
     $cm = $this->get('oro_config.global');
     $stats = $statisticProvider->get();
     $defaultValue = $cm->get(LanguageType::CONFIG_KEY, true);
     // @TODO find better solution
     if ($defaultValue == 'en') {
         $defaultValue = \Locale::composeLocale(['language' => $defaultValue, 'region' => 'US']);
     }
     $configValues = $cm->get(TranslationStatusInterface::CONFIG_KEY);
     $localeChoices = Intl::getLocaleBundle()->getLocaleNames();
     return ['statistic' => $stats, 'defaultLanguage' => $defaultValue, 'config' => (array) $configValues, 'locale' => $localeChoices];
 }
Exemplo n.º 21
0
 /**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     if (null === $value || '' === $value) {
         return;
     }
     if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
         throw new UnexpectedTypeException($value, 'string');
     }
     $value = (string) $value;
     $locales = Intl::getLocaleBundle()->getLocaleNames();
     if (!isset($locales[$value])) {
         $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
     }
 }
Exemplo n.º 22
0
 public function formAddTranslationSubmitted(Form $form)
 {
     $values = $form->getValues();
     try {
         $translation = $this->projectFacade->createTranslation($this->project, $values->lang);
         $this->log($this->project, Activity::CREATE_TRANSLATION, $translation);
         $this->flash(sprintf('Translation for language %s created', Intl::getLocaleBundle()->getLocaleName($values->lang)));
     } catch (ExistingTranslationException $e) {
         $this->flash($e->getMessage(), 'error');
     } catch (InvalidPluralRuleException $e) {
         $this->flash($e->getMessage(), 'error');
     }
     $this->redirect('this');
 }
Exemplo n.º 23
0
 public function testSubmitData()
 {
     $faker = Factory::create();
     $formData = ['locale' => $faker->randomKey(Intl::getLocaleBundle()->getLocaleNames()), 'currency' => $faker->randomKey(Intl::getCurrencyBundle()->getCurrencyNames()), 'username' => $faker->userName, 'email_address' => $faker->email, 'base_url' => $faker->url, 'password' => null];
     $form = $this->factory->create(SystemInformationForm::class, null, ['userCount' => 0]);
     // submit the data to the form directly
     $form->submit($formData);
     $this->assertTrue($form->isSynchronized());
     $this->assertEquals($formData, $form->getData());
     $view = $form->createView();
     $children = $view->children;
     foreach (array_keys($formData) as $key) {
         $this->assertArrayHasKey($key, $children);
     }
 }
Exemplo n.º 24
0
 /**
  * @param FormBuilderInterface $builder
  * @param array                $options
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     if (extension_loaded('intl')) {
         $builder->add('locale', Select2::class, ['choices' => array_flip(Intl::getLocaleBundle()->getLocaleNames()), 'choices_as_values' => true, 'constraints' => new Constraints\NotBlank(['message' => 'Please select a locale']), 'placeholder' => 'Please select a locale']);
     } else {
         $builder->add('locale', null, ['data' => 'en', 'read_only' => true, 'help' => 'The only currently supported locale is "en". To choose a different locale, please install the \'intl\' extension', 'placeholder' => 'Please select a locale']);
     }
     $builder->add('currency', Select2::class, ['choices' => array_flip(Intl::getCurrencyBundle()->getCurrencyNames()), 'choices_as_values' => true, 'constraints' => new Constraints\NotBlank(['message' => 'Please select a currency']), 'placeholder' => 'Please select a currency']);
     $builder->add('base_url', null, ['constraints' => new Constraints\NotBlank(['message' => 'Please set the application base url'])]);
     if (0 === $options['userCount']) {
         $builder->add('username', null, ['constraints' => new Constraints\NotBlank(['message' => 'Please enter a username'])]);
         $builder->add('email_address', EmailType::class, ['constraints' => [new Constraints\NotBlank(['message' => 'Please enter a email']), new Constraints\Email()]]);
         $builder->add('password', RepeatedType::class, ['type' => PasswordType::class, 'invalid_message' => 'The password fields must match.', 'options' => ['attr' => ['class' => 'password-field']], 'required' => true, 'first_options' => ['label' => 'Password'], 'second_options' => ['label' => 'Repeat Password'], 'constraints' => [new Constraints\NotBlank(['message' => 'You must enter a secure password']), new Constraints\Length(['min' => 6])]]);
     }
 }
Exemplo n.º 25
0
 /**
  * @param FormBuilderInterface $builder
  * @param array                $options
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $currencies = Intl::getCurrencyBundle()->getCurrencyNames();
     if (extension_loaded('intl')) {
         $builder->add('locale', 'select2', array('choices' => Intl::getLocaleBundle()->getLocaleNames(), 'constraints' => new Constraints\NotBlank(array('message' => 'Please select a locale')), 'placeholder' => '', 'choices_as_values' => false));
     } else {
         $builder->add('locale', null, array('data' => 'en', 'read_only' => true, 'help' => 'The only currently supported locale is "en". To choose a different locale, please install the \'intl\' extension'));
     }
     $builder->add('currency', 'select2', array('choices' => $currencies, 'constraints' => new Constraints\NotBlank(array('message' => 'Please select a currency')), 'placeholder' => '', 'choices_as_values' => false));
     $builder->add('base_url', null, array('constraints' => new Constraints\NotBlank(array('message' => 'Please set the application base url')), 'data' => $this->request->getSchemeAndHttpHost() . $this->request->getBaseUrl()));
     if (0 === $this->userCount) {
         $builder->add('username', null, array('constraints' => new Constraints\NotBlank(array('message' => 'Please enter a username'))));
         $builder->add('email_address', 'email', array('constraints' => array(new Constraints\NotBlank(array('message' => 'Please enter a email')), new Constraints\Email())));
         $builder->add('password', 'repeated', array('type' => 'password', 'invalid_message' => 'The password fields must match.', 'options' => array('attr' => array('class' => 'password-field')), 'required' => true, 'first_options' => array('label' => 'Password'), 'second_options' => array('label' => 'Repeat Password'), 'constraints' => array(new Constraints\NotBlank(array('message' => 'You must enter a secure password')), new Constraints\Length(array('min' => 6)))));
     }
 }
Exemplo n.º 26
0
 public function testSubmitData()
 {
     $faker = Factory::create();
     $formData = array('locale' => $faker->randomKey(Intl::getLocaleBundle()->getLocaleNames()), 'currency' => $faker->randomKey(Intl::getCurrencyBundle()->getCurrencyNames()), 'username' => $faker->userName, 'email_address' => $faker->email, 'base_url' => $faker->url, 'password' => null);
     $type = new SystemInformationForm($this->getMock('Symfony\\Component\\HttpFoundation\\Request'));
     $form = $this->factory->create($type);
     // submit the data to the form directly
     $form->submit($formData);
     $this->assertTrue($form->isSynchronized());
     $this->assertEquals($formData, $form->getData());
     $view = $form->createView();
     $children = $view->children;
     foreach (array_keys($formData) as $key) {
         $this->assertArrayHasKey($key, $children);
     }
 }
 public function handle($className, Property $property)
 {
     foreach ($this->getConstraintsForProperty($className, $property) as $constraint) {
         if ($constraint instanceof \Symfony\Component\Validator\Constraints\Choice) {
             if ($constraint->callback) {
                 if (!is_callable($choices = $constraint->callback)) {
                     throw new ConstraintDefinitionException('The Choice constraint expects a valid callback');
                 }
                 $choices = call_user_func($choices);
             } else {
                 $choices = $constraint->choices;
             }
             $property->setEnumeration($choices);
         }
         if ($constraint instanceof \Symfony\Component\Validator\Constraints\Locale) {
             $property->setEnumeration(array_keys(Intl::getLocaleBundle()->getLocaleNames()));
         }
         if ($constraint instanceof \Symfony\Component\Validator\Constraints\Length) {
             $property->setMinimum($constraint->min);
             $property->setMaximum($constraint->max);
         }
         if ($constraint instanceof \Symfony\Component\Validator\Constraints\Type) {
             $property->addType($constraint->type);
         }
         if ($constraint instanceof \Symfony\Component\Validator\Constraints\Date) {
             $property->setFormat(Property::FORMAT_DATE);
         }
         if ($constraint instanceof \Symfony\Component\Validator\Constraints\DateTime) {
             $property->setFormat(Property::FORMAT_DATETIME);
         }
         if ($constraint instanceof \Symfony\Component\Validator\Constraints\Time) {
             $property->setFormat(Property::FORMAT_TIME);
         }
         if ($constraint instanceof \Symfony\Component\Validator\Constraints\Email) {
             $property->setFormat(Property::FORMAT_EMAIL);
         }
         if ($constraint instanceof \Symfony\Component\Validator\Constraints\Ip) {
             if ('4' === $constraint->version) {
                 $property->setFormat(Property::FORMAT_IPADDRESS);
             } elseif ('6' === $constraint->version) {
                 $property->setFormat(Property::FORMAT_IPV6);
             }
         }
     }
 }
Exemplo n.º 28
0
 /**
  * @param ListMapper $list
  */
 protected function configureListFields(ListMapper $list)
 {
     $list->add('key', 'string')->add('domain', 'string');
     foreach ($this->managedLocales as $locale) {
         if ($this->request) {
             $localeString = $this->request->getLocale();
         } else {
             $localeString = $locale;
         }
         $localeList = Intl::getLocaleBundle()->getLocaleNames(substr($localeString, 0, 2));
         $fieldDescription = $this->modelManager->getNewFieldDescriptionInstance($this->getClass(), $locale);
         $fieldDescription->setTemplate('NetworkingInitCmsBundle:CRUD:base_inline_translation_field.html.twig');
         $fieldDescription->setOption('locale', $locale);
         $fieldDescription->setOption('editable', $this->editableOptions);
         $fieldDescription->setOption('label', $localeList[$locale]);
         $list->add($fieldDescription);
     }
 }
Exemplo n.º 29
0
 public function log(User $user, Project $project, $activity, $object)
 {
     $log = new ActivityLog();
     $message = Activity::getMessage($activity);
     $args = [];
     $projectName = $project->getName();
     switch ($activity) {
         case Activity::ADD_COLLABORATOR:
         case Activity::REMOVE_COLLABORATOR:
             $args[] = $object->getUser()->getNick();
             $args[] = $object->getLevel();
             break;
         case Activity::REMOVE_TRANSLATION:
         case Activity::CREATE_TRANSLATION:
             $args[] = Intl::getLocaleBundle()->getLocaleName($object->getLang());
             break;
         case Activity::DELETE_MESSAGE:
         case Activity::ADD_MESSAGE:
             $args[] = $object->getSingular();
             break;
         case Activity::IMPORT_TEMPLATE:
             $args[] = $object;
             //count of imported messages
             $args[] = count($project->getTemplateMessages());
             //total count
             break;
         case Activity::TRANSLATE_SINGULAR:
             $args[] = $object->getSingular();
             $translations = $object->getTranslations();
             $args[] = array_shift($translations);
             break;
         case Activity::TRANSLATE_PLURAL:
             $args[] = $object->getPlural();
             $args[] = implode(', ', $object->getTranslations());
             break;
         case \Activity::DELETE_PROJECT:
             $project = NULL;
             break;
     }
     $log->setActorId($user->getId())->setActorNick($user->getNick())->setProjectName($projectName)->setActivity($activity)->setMessage($message)->setArgs($args);
     $this->dm->persist($log);
     $this->dm->flush();
 }
Exemplo n.º 30
0
 /**
  * Provide an array of locales where the locale is the key and the label is
  * the value for easy display in a dropdown select for example
  * example: array('de_CH' => 'Deutsch', 'en_GB' => 'English')
  *
  * @return array
  */
 protected function getLocaleChoices()
 {
     $localeChoices = array();
     if (!$this->request) {
         return array();
     }
     if (!$this->getRequest()->get('locale')) {
         $locale = $this->getRequest()->getLocale();
     } else {
         $locale = $this->getRequest()->get('locale');
     }
     if (is_array($locale) && array_key_exists('value', $locale)) {
         $locale = $locale['value'];
     }
     $localeList = Intl::getLocaleBundle()->getLocaleNames(substr($locale, 0, 2));
     foreach ($this->languages as $language) {
         $localeChoices[$language['locale']] = $localeList[$language['locale']];
     }
     return $localeChoices;
 }