public function notify(RequestVerifiedEvent $event)
 {
     $payment = $event->getPayment();
     $status = $event->getStatus()->getValue();
     switch ($status) {
         case GetHumanStatus::STATUS_AUTHORIZED:
         case GetHumanStatus::STATUS_CAPTURED:
         case GetHumanStatus::STATUS_REFUNDED:
             $this->repository->clearCart();
             $type = 'success';
             break;
         case GetHumanStatus::STATUS_CANCELED:
         case GetHumanStatus::STATUS_EXPIRED:
         case GetHumanStatus::STATUS_FAILED:
             $type = 'danger';
             break;
         case GetHumanStatus::STATUS_PENDING:
         case GetHumanStatus::STATUS_SUSPENDED:
             $this->repository->clearCart();
             $type = 'warning';
             break;
         case GetHumanStatus::STATUS_NEW:
         case GetHumanStatus::STATUS_UNKNOWN:
             $this->repository->clearCart();
             $type = 'info';
             break;
         default:
             throw new \RuntimeException('Unknown status ' . $status);
     }
     $formatter = new \NumberFormatter($this->translator->getLocale(), \NumberFormatter::CURRENCY);
     $this->session->getFlashBag()->add($type, $this->translator->trans('flash.payment.' . $type, ['%status%' => $this->translator->trans('meta.status.' . $status), '%amount%' => $formatter->formatCurrency($payment->getTotalAmount() / 100, $payment->getCurrencyCode())]));
 }
 /**
  * Inject Translator locale into loaded object.
  *
  * @param LifecycleEventArgs $args
  */
 public function postLoad(LifecycleEventArgs $args)
 {
     $object = $args->getObject();
     if ($object instanceof LocaleAware) {
         $object->setCurrentLocale($this->translator->getLocale());
     }
 }
Esempio n. 3
0
 /**
  * Executes controller.
  *
  * @param InputInterface  $input
  * @param OutputInterface $output
  *
  * @return null|integer
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     if (!$input->getOption('story-syntax')) {
         return null;
     }
     $output->getFormatter()->setStyle('gherkin_keyword', new OutputFormatterStyle('green', null, array('bold')));
     $output->getFormatter()->setStyle('gherkin_comment', new OutputFormatterStyle('yellow'));
     $story = $this->keywordsDumper->dump($this->translator->getLocale());
     $story = preg_replace('/^\\#.*/', '<gherkin_comment>$0</gherkin_comment>', $story);
     $output->writeln($story);
     $output->writeln('');
     return 0;
 }
 /**
  * Format the given value.
  *
  * @param mixed   $value
  * @param string  $valueCurrency  $value currency code
  * @param boolean $decimal        show decimal part
  * @param boolean $symbol         show currency symbol
  * @return string
  */
 public function format($value, $valueCurrency = null, $decimal = true, $symbol = true)
 {
     if (null === $valueCurrency) {
         $valueCurrency = $this->getConverter()->getDefaultCurrency();
     }
     $formatter = new \NumberFormatter($this->translator->getLocale(), $symbol ? \NumberFormatter::CURRENCY : \NumberFormatter::PATTERN_DECIMAL);
     $value = $formatter->formatCurrency($value, $valueCurrency);
     if (!$decimal) {
         $value = preg_replace('/[.,]00((?=\\D)|$)/', '', $value);
     }
     $value = str_replace(array('EU', 'UK', 'US'), '', $value);
     return $value;
 }
 /**
  * @param array $translations
  */
 public function saveTranslations(array $translations)
 {
     if (!$translations) {
         return;
     }
     $locale = $this->translator->getLocale();
     $entities = [];
     foreach ($translations as $key => $value) {
         $entities[] = $this->createTranslationEntity($key, $value, $locale);
     }
     // mark translation cache dirty
     $this->translationCache->updateTimestamp($locale);
     $this->getTranslationManager()->flush($entities);
 }
 /**
  * @param mixed $value
  * @param array $options
  * @return string
  * @throws \Exception
  */
 public function renderValue($value, array $options = [])
 {
     if ($value instanceof \DateTime) {
         if (!empty($options['date_format'])) {
             return $value->format($options['date_format']);
         }
         $dateType = IntlDateFormatter::MEDIUM;
         $timeType = IntlDateFormatter::SHORT;
         if (array_key_exists('date_type', $options) && $options['date_type'] !== null && $options['date_type'] !== '') {
             $dateType = $options['date_type'];
         }
         if (array_key_exists('time_type', $options) && $options['time_type'] !== null && $options['time_type'] !== '') {
             $dateType = $options['time_type'];
         }
         $dateFormatter = new IntlDateFormatter($this->translator->getLocale(), $dateType, $timeType);
         return $dateFormatter->format($value);
     }
     if (is_int($value)) {
         return $value;
     }
     if (is_float($value)) {
         if (array_key_exists('decimals', $options) || array_key_exists('dec_point', $options) || array_key_exists('thousands_sep', $options)) {
             $decimals = array_key_exists('decimals', $options) ? $options['decimals'] : 2;
             $decPoint = array_key_exists('dec_point', $options) ? $options['dec_point'] : '.';
             $thousandsSep = array_key_exists('thousands_sep', $options) ? $options['thousands_sep'] : ',';
             return number_format($value, $decimals, $decPoint, $thousandsSep);
         }
         $numberFormatter = new NumberFormatter($this->translator->getLocale(), NumberFormatter::DECIMAL);
         return $numberFormatter->format($value);
     }
     if (is_array($value) || $value instanceof \Traversable) {
         $items = [];
         foreach ($value as $item) {
             $items[] = $this->renderValue($item, $options);
         }
         $glue = ', ';
         if (!empty($options['array_glue'])) {
             $glue = $options['array_glue'];
         }
         return implode($glue, $items);
     }
     if (is_callable($value)) {
         return $value($options);
     }
     if (is_bool($value)) {
         return $this->translator->trans($value ? 'sidus.datagrid.boolean.yes' : 'sidus.datagrid.boolean.no');
     }
     return $value;
 }
 public function metaTagsHtml($defaults = true, array $arguments = array(), $canonical = true)
 {
     $locale = $this->translator->getLocale();
     $currentLang = substr($locale, 0, 2);
     if (!isset($arguments['pre'])) {
         $arguments['pre'] = sprintf("\n%8s", ' ');
     }
     $headers = self::initMetaTagString();
     if ($defaults) {
         $headers .= $arguments['pre'] . '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
         $headers .= $arguments['pre'] . '<meta http-equiv="content-language" content="' . $currentLang . '" />';
         $headers .= $arguments['pre'] . '<meta name="DC.language" scheme="RFC3066" content="' . $currentLang . '" />';
     }
     $key = $this->keyGenerator->generateMetaTagKey($this->container->get('request'), $this->container->get('router'), $locale);
     $obj = $this->manager->findMetaTag($key, $locale);
     if ($obj) {
         $headers .= $this->metaTagToHtml($obj, $arguments);
     } else {
         $tags = $arguments;
         unset($tags['pre']);
         $headers .= MetaTagToHtmlRenderer::createMetaTags($arguments['pre'], $tags, $this);
     }
     if ($canonical) {
         $headers .= $arguments['pre'] . $this->canonicalTagsHtml($this->getRequest()->getPathInfo());
     }
     return $headers;
 }
 /**
  * Get the route prefix.
  *
  * @return string
  */
 public function routePrefix()
 {
     $driver = $this->getDriver();
     if ($driver instanceof ShouldPrefixRoute) {
         return $driver->routePrefix($this->translator->getLocale());
     }
     return '';
 }
Esempio n. 9
0
 /**
  * renders content with the real website controller.
  *
  * @param PageBridge $content
  * @param bool       $partial
  *
  * @return string
  */
 public function render(PageBridge $content, $partial = false)
 {
     // set active theme
     $webspace = $this->webspaceManager->findWebspaceByKey($content->getWebspaceKey());
     $this->activeTheme->setName($webspace->getTheme()->getKey());
     // get controller and invoke action
     $request = new Request();
     $request->attributes->set('_controller', $content->getController());
     $controller = $this->controllerResolver->getController($request);
     // prepare locale for translator and request
     $request->setLocale($content->getLanguageCode());
     $localeBefore = $this->translator->getLocale();
     $this->translator->setLocale($content->getLanguageCode());
     $this->requestStack->push($request);
     /** @var Response $response */
     $response = $controller[0]->{$controller[1]}($content, true, $partial);
     // roll back
     $this->requestStack->pop();
     $this->translator->setLocale($localeBefore);
     return $response->getContent();
 }
 /**
  * Post submit event handler
  *
  * @param FormEvent $event
  *
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function postSubmit(FormEvent $event)
 {
     $form = $event->getForm();
     $configModel = $form->getConfig()->getOption('config_model');
     if (!$configModel instanceof FieldConfigModel) {
         return;
     }
     if (!in_array($configModel->getType(), ['enum', 'multiEnum'])) {
         return;
     }
     if (!$form->isValid()) {
         return;
     }
     $data = $event->getData();
     $enumConfig = $configModel->toArray('enum');
     $enumName = $this->getValue($data['enum'], 'enum_name');
     $enumCode = $this->getValue($enumConfig, 'enum_code');
     if (empty($enumCode)) {
         $enumCode = $enumName !== null ? ExtendHelper::buildEnumCode($enumName) : ExtendHelper::generateEnumCode($configModel->getEntity()->getClassName(), $configModel->getFieldName());
     }
     $locale = $this->translator->getLocale();
     $enumValueClassName = ExtendHelper::buildEnumValueClassName($enumCode);
     $enumConfigProvider = $this->configManager->getProvider('enum');
     if ($enumConfigProvider->hasConfig($enumValueClassName)) {
         // existing enum
         if ($configModel->getId()) {
             if ($enumName !== null) {
                 $this->enumSynchronizer->applyEnumNameTrans($enumCode, $enumName, $locale);
             }
             $enumOptions = $this->getValue($data['enum'], 'enum_options');
             if ($enumOptions !== null) {
                 $this->enumSynchronizer->applyEnumOptions($enumValueClassName, $enumOptions, $locale);
             }
             $enumPublic = $this->getValue($data['enum'], 'enum_public');
             if ($enumPublic !== null) {
                 $this->enumSynchronizer->applyEnumEntityOptions($enumValueClassName, $enumPublic);
             }
         }
         unset($data['enum']['enum_name']);
         unset($data['enum']['enum_options']);
         unset($data['enum']['enum_public']);
         $event->setData($data);
     } else {
         // new enum
         $this->sortOptions($data['enum']['enum_options']);
         $data['enum']['enum_locale'] = $locale;
         $event->setData($data);
     }
 }
 public function finishView(FormView $view, FormInterface $form, array $options)
 {
     if ($view->children['country']->vars['choice_translation_domain'] === false) {
         return;
     }
     $collator = new \Collator($this->translator->getLocale());
     $translator = $this->translator;
     $sortFunction = function ($a, $b) use($collator, $translator) {
         return $collator->compare($translator->trans($a->label), $translator->trans($b->label));
     };
     usort($view->children['country']->vars['choices'], $sortFunction);
     if (array_key_exists('state', $view->children) && $view->children['state']->vars['choice_translation_domain']) {
         usort($view->children['state']->vars['choices'], $sortFunction);
     }
     if (array_key_exists('city', $view->children) && $view->children['city']->vars['choice_translation_domain']) {
         usort($view->children['city']->vars['choices'], $sortFunction);
     }
 }
 public function onKernelView(GetResponseForControllerResultEvent $event)
 {
     $request = $event->getRequest();
     if (!$this->isApiRequest($request)) {
         return;
     }
     // we now only use json, if more formats will be added, then it can check request uri or headers
     // and only presenter object allowed as controller result etc
     $data = $event->getControllerResult();
     switch (true) {
         case is_array($data):
         case $data instanceof JsonSerializable:
             $response = new JsonResponse($data);
             break;
         case is_string($data):
             $response = new Response($data);
             $response->headers->set('Content-Type', 'application/json');
             break;
         default:
             throw new \UnexpectedValueException("Response type: " . gettype($data) . " from controller was not expected.");
     }
     $response->headers->set('Language', $this->translator->getLocale());
     $event->setResponse($response);
 }
 /**
  * {@inheritdoc}
  */
 public function normalize($version, $format = null, array $context = [])
 {
     $context = ['locale' => $this->translator->getLocale()];
     return ['id' => $version->getId(), 'author' => $this->normalizeAuthor($version->getAuthor()), 'resource_id' => (string) $version->getResourceId(), 'snapshot' => $version->getSnapshot(), 'changeset' => $this->convertChangeset($version->getChangeset(), $context), 'context' => $version->getContext(), 'version' => $version->getVersion(), 'logged_at' => $this->datetimePresenter->present($version->getLoggedAt(), $context), 'pending' => $version->isPending()];
 }
Esempio n. 14
0
 /**
  * @param MetaTitleRepository        $metaTitleRepo
  * @param BundleInformationInterface $bundleInfo
  * @param TranslatorInterface        $translator
  */
 public function __construct(MetaTitleRepository $metaTitleRepo, BundleInformationInterface $bundleInfo, TranslatorInterface $translator)
 {
     $this->setMetaTitleRepo($metaTitleRepo)->setLocale($translator->getLocale())->extractBundleParts($bundleInfo);
 }
 /**
  * @return string
  */
 public function getAttributeInformationUrl()
 {
     return $this->attributeInformationUrls[$this->translator->getLocale()];
 }
 /**
  * {@inheritdoc}
  */
 public function getLocale()
 {
     return $this->symfonyTranslator->getLocale();
 }
 function it_proxies_choice_translating_with_modified_default_locale(TranslatorInterface $translator, ThemeContextInterface $themeContext, ThemeInterface $theme)
 {
     $themeContext->getTheme()->willReturn($theme);
     $theme->getName()->willReturn('theme/name');
     $translator->getLocale()->willReturn('defaultlocale');
     $translator->transChoice('id', 2, ['param'], 'domain', 'defaultlocale@theme-name')->willReturn('translated string');
     $this->transChoice('id', 2, ['param'], 'domain')->shouldReturn('translated string');
 }
Esempio n. 18
0
 function it_proxies_getting_the_locale_to_the_decorated_translator(TranslatorInterface $translator)
 {
     $translator->getLocale()->willReturn('pl_PL');
     $this->getLocale()->shouldReturn('pl_PL');
 }
Esempio n. 19
0
 /**
  * {@inheritdoc}
  */
 public function getLocale()
 {
     $this->initialize();
     return $this->translator->getLocale();
 }
Esempio n. 20
0
 /**
  * Inject translator so it can pass translated strings to js
  *
  * @param TranslatorInterface $translator
  *
  * @return JsVars
  */
 public function enableTranslator(TranslatorInterface $translator)
 {
     $this->translator = $translator;
     $this->translations = array();
     $this->_locale = $translator->getLocale();
     return $this;
 }
 /**
  * {@inheritdoc}
  *
  * @throws \InvalidArgumentException If the target locales parameter is used improperly.
  */
 public function formatTranslatableViolationList(ConstraintViolationListInterface $violations, bool $sortProperties = true, $useAllLanguages = true, array $targetLocales = [], string $domain = 'messages') : array
 {
     $hasLocales = count($targetLocales) > 0;
     if (!$useAllLanguages && $hasLocales) {
         throw new \InvalidArgumentException('Wrong usage of $targetLocales: If the default locale is the only target, $targetLocales must not have any values!');
     }
     if ($useAllLanguages && !$hasLocales) {
         throw new \InvalidArgumentException('Wrong usage of $targetLocales: If the all locales should be rendered, $targetLocales must be given!');
     }
     $fixtures = [];
     foreach ($violations as $violation) {
         // Every translation entry (whether sorted by properties in deeper levels or as top level)
         // should provide a basic structure.
         switch (true) {
             // If sorted by $targetLanguages, it may look like this:
             //
             // [
             //   'de' => ['Deutscher Text'],
             //   'en' => ['English text'],
             // ]
             //
             // When sorting by property, the structure will be merged recursively into the property list:
             //
             // [
             //   'property' => [
             //     // this is the structure merged into the property.
             //     'de' => ['Deutscher Text'],
             //     'en' => ['English text'],
             //   ]
             // ]
             case $useAllLanguages:
                 $structure = array_reduce($targetLocales, function (array $carry, string $locale) use($violation, $domain) : array {
                     if (!isset($carry[$locale])) {
                         $carry[$locale] = [];
                     }
                     if ($locale === $this->translator->getLocale()) {
                         $carry[$locale][] = $violation->getMessage();
                     } else {
                         $messageTemplate = $violation->getMessageTemplate();
                         $parameters = $violation->getParameters();
                         if ($plural = $violation->getPlural()) {
                             try {
                                 $message = $this->translator->transChoice($messageTemplate, $plural, $parameters, $domain, $locale);
                             } catch (\InvalidArgumentException $ex) {
                                 // we do nothing here.
                                 // If the pluralization fails, the default translation method will be used.
                                 $message = $this->translator->trans($messageTemplate, $parameters, $domain, $locale);
                             }
                         } else {
                             $message = $this->translator->trans($messageTemplate, $parameters, $domain, $locale);
                         }
                         $carry[$locale][] = $message;
                     }
                     return $carry;
                 }, []);
                 break;
             default:
                 // If the default language is in use and nothing more, the structure looks like this:
                 //
                 // ['Message in the currently selected language']
                 $structure = [$violation->getMessage()];
         }
         if (!$sortProperties) {
             $fixtures = array_merge_recursive($fixtures, $structure);
         } else {
             $propertyPath = $violation->getPropertyPath();
             if (!isset($fixtures[$violation->getPropertyPath()])) {
                 $fixtures[$violation->getPropertyPath()] = [];
             }
             $fixtures[$propertyPath] = array_merge_recursive($fixtures[$propertyPath], $structure);
         }
     }
     return $fixtures;
 }
 /**
  * @param string $message
  * @param string $locale
  * @return string
  */
 private function translate($message, $locale)
 {
     list($domain, $id) = $this->messageAnalyzer->extractDomainFromMessage($message);
     return $this->translator->trans($id, [], $domain, $locale ?: $this->translator->getLocale());
 }
Esempio n. 23
0
 /**
  * {@inheritdoc}
  */
 public function getLocale()
 {
     return $this->translator->getLocale();
 }
 /**
  * Evaluates the locale.
  *
  * @param NotificationInput $input
  *
  * @return string
  */
 private function getLocale(NotificationInput $input) : string
 {
     return null === $input->getLanguage() ? $this->translator->getLocale() : $input->getLanguage();
 }