public function format(DateDiffResult $result)
 {
     if ($result->getKey() === DateDiffResult::FULL_DATE) {
         return $result->getRequest()->getDate()->format($this->dateFormat);
     }
     return $this->translatorInterface->transChoice($result->getKey(), $result->getValue(), $this->getPlaceholders($result), $this->domain);
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     if (empty($options['data_class'])) {
         return;
     }
     $className = $options['data_class'];
     if (!$this->doctrineHelper->isManageableEntity($className)) {
         return;
     }
     if (!$this->entityConfigProvider->hasConfig($className)) {
         return;
     }
     $uniqueKeys = $this->entityConfigProvider->getConfig($className)->get('unique_key');
     if (empty($uniqueKeys)) {
         return;
     }
     /* @var \Symfony\Component\Validator\Mapping\ClassMetadata $validatorMetadata */
     $validatorMetadata = $this->validator->getMetadataFor($className);
     foreach ($uniqueKeys['keys'] as $uniqueKey) {
         $fields = $uniqueKey['key'];
         $labels = array_map(function ($fieldName) use($className) {
             $label = $this->entityConfigProvider->getConfig($className, $fieldName)->get('label');
             return $this->translator->trans($label);
         }, $fields);
         $constraint = new UniqueEntity(['fields' => $fields, 'errorPath' => '', 'message' => $this->translator->transChoice('oro.entity.validation.unique_field', sizeof($fields), ['%field%' => implode(', ', $labels)])]);
         $validatorMetadata->addConstraint($constraint);
     }
 }
 private function translateMessage(TranslatableNotificationMessage $message)
 {
     if ($message->number !== null) {
         return $this->translator->transChoice($message->message, (int) $message->number, $message->translationParams, $message->domain);
     }
     return $this->translator->trans($message->message, $message->translationParams, $message->domain);
 }
 /**
  * @param float|integer $value
  * @param ProductUnit $unit
  * @param boolean $isShort
  * @return string
  */
 protected function formatData($value, ProductUnit $unit, $isShort = false)
 {
     if (!is_numeric($value)) {
         throw new \InvalidArgumentException(sprintf('The parameter "value" must be a numeric, but it is of type %s.', gettype($value)));
     }
     $translationKey = sprintf('orob2b.product_unit.%s.value.' . ($isShort ? 'short' : 'full'), $unit->getCode());
     return $this->translator->transChoice($translationKey, $value, ['%count%' => $value]);
 }
 /**
  * @param int $shoppingListId
  * @param int $entitiesCount
  * @param null|string $transChoiceKey
  * @return string
  */
 public function getSuccessMessage($shoppingListId = null, $entitiesCount = 0, $transChoiceKey = null)
 {
     $message = $this->translator->transChoice($transChoiceKey ?: 'orob2b.shoppinglist.actions.add_success_message', $entitiesCount, ['%count%' => $entitiesCount]);
     if ($shoppingListId && $entitiesCount > 0) {
         $message = sprintf('%s (<a href="%s">%s</a>).', $message, $this->router->generate('orob2b_shopping_list_frontend_view', ['id' => $shoppingListId]), $linkTitle = $this->translator->trans('orob2b.shoppinglist.actions.view'));
     }
     return $message;
 }
 /**
  * @param $collection
  * @param $limit
  * @param $count
  *
  * @return string
  */
 private function formatCommaSeparatedWithLimit($collection, $limit, $count)
 {
     $display = array_map(function ($element) {
         return (string) $element;
     }, array_slice($collection, 0, $limit));
     $moreCount = $count - count($display);
     return $this->translator->transChoice('comma_separated_with_limit', $moreCount, array('%list%' => implode(', ', $display), '%count%' => $moreCount), $this->catalogue);
 }
 protected function getResponse(MassActionHandlerArgs $args, $count = 0)
 {
     $massAction = $args->getMassAction();
     $responseMessage = $massAction->getOptions()->offsetGetByPath('[messages][success]', $this->responseMessage);
     $successful = $count > 0;
     $options = ['count' => $count];
     return new MassActionResponse($successful, $this->translator->transChoice($responseMessage, $count, ['%count%' => $count]), $options);
 }
 /**
  * @param PreciseDifference $difference
  * @param string            $locale
  *
  * @return string
  */
 public function formatDifference(PreciseDifference $difference, $locale = 'en')
 {
     $diff = array();
     foreach ($difference->getCompoundResults() as $result) {
         $diff[] = $this->translator->transChoice('compound.' . $result->getUnit()->getName(), $result->getQuantity(), array('%count%' => $result->getQuantity()), 'difference', $locale);
     }
     return $this->translator->trans('compound.' . ($difference->isPast() ? 'past' : 'future'), array('%value%' => implode(', ', $diff)), 'difference', $locale);
 }
 private function trans($context, $args, $count, $bundle, $locale)
 {
     if (is_null($count)) {
         $trans = $this->translator->trans($context, $args, $bundle, $locale);
     } else {
         $trans = $this->translator->transChoice($context, $count, $args, $bundle, $locale);
     }
     return $trans;
 }
 /**
  * @param PreciseDifference $difference
  * @param string $locale
  * @return string
  */
 public function formatDifference(PreciseDifference $difference, $locale = 'en')
 {
     $diff = array();
     foreach ($difference->getCompoundResults() as $result) {
         $diff[] = $this->translator->transChoice("compound." . $result->getUnit()->getName(), $result->getQuantity(), array('%count%' => $result->getQuantity()), 'difference', $locale);
     }
     $suffix = $difference->isPast() ? 'compound.ago' : 'compound.from_now';
     return join(", ", $diff) . ' ' . $this->translator->trans($suffix, array(), 'difference', $locale);
 }
 /**
  * Get translated age string.
  *
  * @param string|\DateTime $date
  * @param array $options
  * @return string
  */
 public function getAgeAsString($date, $options)
 {
     $dateDiff = $this->getDateDiff($date, $options);
     if (!$dateDiff->invert) {
         $age = $dateDiff->y;
         return $this->translator->transChoice('oro.age', $age, array('%count%' => $age), 'messages');
     } else {
         return isset($options['default']) ? $options['default'] : '';
     }
 }
Exemple #12
0
 /**
  * {@inheritdoc}
  */
 public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null)
 {
     $possibleIds = $this->getPossibleIds($id);
     foreach ($possibleIds as $possibleId) {
         $translation = $this->translator->transChoice($possibleId, $number, $parameters, $domain, $locale);
         if ($translation !== $possibleId) {
             return $translation;
         }
     }
     return $id;
 }
Exemple #13
0
 protected function getPluralizedInterval($count, $invert, $unit)
 {
     if ($this->translator) {
         $id = sprintf('diff.%s.%s', $invert ? 'in' : 'ago', $unit);
         return $this->translator->transChoice($id, $count, array('%count%' => $count), 'date');
     }
     if (1 !== $count) {
         $unit .= 's';
     }
     return $invert ? "in {$count} {$unit}" : "{$count} {$unit} ago";
 }
 public function visitMenuItem(MenuItem $item)
 {
     $domain = $item->getExtra('translation_domain');
     $parameters = $item->getExtra('translation_parameters');
     if (false === $parameters) {
         return;
     } elseif (!is_array($parameters)) {
         $parameters = [];
     }
     $id = $item->getLabel();
     if (null !== ($number = $item->getExtra('translation_number'))) {
         $item->setLabel($this->translator->transChoice($id, $number, $parameters, $domain));
     } else {
         $item->setLabel($this->translator->trans($id, $parameters, $domain));
     }
 }
Exemple #15
0
 /**
  * @param object $entity
  * @param string $scope
  * @return string|null
  */
 public function getInfoMessage($entity, $scope = EntityPaginationManager::VIEW_SCOPE)
 {
     $entityName = ClassUtils::getClass($entity);
     // info message should be shown only once for each scope
     if (false !== $this->storage->isInfoMessageShown($entityName, $scope)) {
         return null;
     }
     $viewCount = $this->navigation->getTotalCount($entity, EntityPaginationManager::VIEW_SCOPE);
     $editCount = $this->navigation->getTotalCount($entity, EntityPaginationManager::EDIT_SCOPE);
     if (!$viewCount || !$editCount || $viewCount == $editCount) {
         return null;
     }
     $message = '';
     $count = null;
     // if scope is changing from "view" to "edit" and number of entities is decreased
     if ($scope == EntityPaginationManager::EDIT_SCOPE) {
         if ($editCount < $viewCount) {
             $message .= $this->translator->trans('oro.entity_pagination.message.stats_changed_view_to_edit') . ' ';
         }
         $count = $editCount;
     } elseif ($scope == EntityPaginationManager::VIEW_SCOPE) {
         $count = $viewCount;
     }
     if (!$count) {
         return null;
     }
     $message .= $this->translator->transChoice($this->getStatsMessage($scope), $count, ['%count%' => $count]);
     $this->storage->setInfoMessageShown($entityName, $scope);
     return $message;
 }
 /**
  * @param string $id
  * @param int    $number
  * @param array  $parameters
  * @param null   $domain
  * @param null   $locale
  * @return string
  */
 public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
 {
     $ret = $this->translator->transChoice($id, $number, $parameters, $domain, $locale);
     if ($this->remember) {
         $this->rememberCache[$id] = array('parameters' => $parameters, 'domain' => $domain, 'locale' => $locale, 'result' => $ret, 'number' => $number);
     }
     return $ret;
 }
 /**
  * @param MassActionMediatorInterface $mediator
  * @param int                         $entitiesCount
  *
  * @return MassActionResponse
  */
 protected function getResponse(MassActionMediatorInterface $mediator, $entitiesCount = 0)
 {
     $massAction = $mediator->getMassAction();
     $responseMessage = $massAction->getOptions()->offsetGetByPath('[messages][success]', $this->responseMessage);
     $successful = $entitiesCount > 0;
     $options = ['count' => $entitiesCount];
     return new MassActionResponse($successful, $this->translator->transChoice($responseMessage, $entitiesCount, ['%count%' => $entitiesCount]), $options);
 }
 /**
  * {@inheritdoc}
  */
 public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
 {
     $id = (string) $id;
     if (!$domain) {
         $domain = 'messages';
     }
     $catalogue = $this->getCatalogue($locale);
     if ($catalogue->defines($id, $domain)) {
         return $this->symfonyTranslator->transChoice($id, $number, $parameters, $domain, $locale);
     }
     $locale = $catalogue->getLocale();
     if ($locale === $this->defaultLocale) {
         // we cant do anything...
         return $id;
     }
     $orgString = $this->symfonyTranslator->transChoice($id, $number, $parameters, $domain, $this->defaultLocale);
     return $this->translateWithSubstitutedParameters($orgString, $locale, $parameters);
 }
 /**
  * @param string $expected
  * @param array $config
  */
 private function configureTranslator($expected, array $config)
 {
     switch ($config['method']) {
         case self::TRANSLATOR_METHOD_TRANSCHOICE:
             $this->translator->transChoice($config['id'], $config['count'], $config['params'], 'validators')->shouldBeCalled()->willReturn($expected);
             break;
         default:
             $this->translator->trans($config['id'], $config['params'], 'validators')->shouldBeCalled()->willReturn($expected);
     }
 }
 /**
  * This function exists to support Symfony 2.3
  *
  * @param string $message
  * @param string $defaultMessage
  * @param int $count
  * @param array $arguments
  * @param string $domain
  * @param string $locale
  *
  * @return string
  */
 private function transchoiceWithDefaultLegacy($message, $defaultMessage, $count, array $arguments, $domain, $locale)
 {
     try {
         $translatedMessage = $this->translator->transChoice($message, $count, array_merge(array('%count%' => $count), $arguments), $domain, $locale);
         if ($translatedMessage !== $message) {
             return $translatedMessage;
         }
     } catch (\InvalidArgumentException $e) {
     }
     return $this->translator->transChoice($defaultMessage, $count, array_merge(array('%count%' => $count), $arguments), $domain, $locale);
 }
 /**
  * @param QuoteProductOffer $item
  * @return string
  */
 public function formatOffer(QuoteProductOffer $item)
 {
     switch ($item->getPriceType()) {
         case QuoteProductOffer::PRICE_TYPE_BUNDLED:
             $transConstant = 'orob2b.sale.quoteproductoffer.item_bundled';
             break;
         default:
             $transConstant = 'orob2b.sale.quoteproductoffer.item';
     }
     $str = $this->translator->transChoice($transConstant, (int) $item->isAllowIncrements(), ['{units}' => $this->formatProductUnit($item), '{price}' => $this->formatPrice($item), '{unit}' => $this->formatUnitCode($item)]);
     return $str;
 }
 /**
  * @param string   $domain
  * @param string   $id
  * @param string[] $parameters
  * @param null|int $number
  */
 protected function setVerboseMessage($domain, $id, array $parameters = [], $number = null)
 {
     if (null === $number) {
         $message = static::$translator->trans($id, $parameters, $domain, 'en');
     } else {
         $message = static::$translator->transChoice($id, $number, $parameters, $domain, 'en');
     }
     $this->verboseMessage = '[Exception] ' . get_class($this) . PHP_EOL;
     $this->verboseMessage .= '[Message] ' . $message . PHP_EOL;
     $this->verboseMessage .= '[File] ' . $this->file . PHP_EOL;
     $this->verboseMessage .= '[Line] ' . $this->line . PHP_EOL;
     $this->verboseMessage .= '[Stack Trace]' . PHP_EOL . $this->getTraceAsString() . PHP_EOL;
 }
 /**
  * {@inheritdoc}
  */
 public function addViolation()
 {
     if (null === $this->plural) {
         $translatedMessage = $this->translator->trans($this->message, $this->parameters, $this->translationDomain);
     } else {
         try {
             $translatedMessage = $this->translator->transChoice($this->message, $this->plural, $this->parameters, $this->translationDomain);
         } catch (\InvalidArgumentException $e) {
             $translatedMessage = $this->translator->trans($this->message, $this->parameters, $this->translationDomain);
         }
     }
     $this->violations->add(new ConstraintViolation($translatedMessage, $this->message, $this->parameters, $this->root, $this->propertyPath, $this->invalidValue, $this->plural, $this->code, $this->constraint, $this->cause));
 }
Exemple #24
0
 /**
  * Prints scenario and step counters.
  *
  * @param OutputPrinter $printer
  * @param string        $intro
  * @param array         $stats
  */
 public function printCounters(OutputPrinter $printer, $intro, array $stats)
 {
     $stats = array_filter($stats, function ($count) {
         return 0 !== $count;
     });
     if (0 === count($stats)) {
         $totalCount = 0;
     } else {
         $totalCount = array_sum($stats);
     }
     $detailedStats = array();
     foreach ($stats as $resultCode => $count) {
         $style = $this->resultConverter->convertResultCodeToString($resultCode);
         $transId = $style . '_count';
         $message = $this->translator->transChoice($transId, $count, array('%1%' => $count), 'output');
         $detailedStats[] = sprintf('{+%s}%s{-%s}', $style, $message, $style);
     }
     $message = $this->translator->transChoice($intro, $totalCount, array('%1%' => $totalCount), 'output');
     $printer->write($message);
     if (count($detailedStats)) {
         $printer->write(sprintf(' (%s)', implode(', ', $detailedStats)));
     }
     $printer->writeln();
 }
Exemple #25
0
 /**
  * Create a sort url for the field named $title
  * and identified by $key which consists of
  * alias and field. $options holds all link
  * parameters like "alt, class" and so on.
  *
  * $key example: "article.title"
  *
  * @param string $title
  * @param string $key
  * @param array $options
  * @param array $params
  * @return array
  */
 public function sortable($pagination, $title, $key, $options = array(), $params = array())
 {
     $options = array_merge(array('absolute' => false, 'translationParameters' => array(), 'translationDomain' => null, 'translationCount' => null), $options);
     $params = array_merge($pagination->getParams(), $params);
     $direction = isset($options[$pagination->getPaginatorOption('sortDirectionParameterName')]) ? $options[$pagination->getPaginatorOption('sortDirectionParameterName')] : (isset($options['defaultDirection']) ? $options['defaultDirection'] : 'asc');
     $sorted = $pagination->isSorted($key, $params);
     if ($sorted) {
         $direction = $params[$pagination->getPaginatorOption('sortDirectionParameterName')];
         $direction = strtolower($direction) == 'asc' ? 'desc' : 'asc';
         $class = $direction == 'asc' ? 'desc' : 'asc';
         if (isset($options['class'])) {
             $options['class'] .= ' ' . $class;
         } else {
             $options['class'] = $class;
         }
     } else {
         $options['class'] = 'sortable';
     }
     if (is_array($title) && array_key_exists($direction, $title)) {
         $title = $title[$direction];
     }
     $params = array_merge($params, array($pagination->getPaginatorOption('sortFieldParameterName') => $key, $pagination->getPaginatorOption('sortDirectionParameterName') => $direction, $pagination->getPaginatorOption('pageParameterName') => 1));
     $options['href'] = $this->routerHelper->generate($pagination->getRoute(), $params, $options['absolute']);
     if (null !== $options['translationDomain']) {
         if (null !== $options['translationCount']) {
             $title = $this->translator->transChoice($title, $options['translationCount'], $options['translationParameters'], $options['translationDomain']);
         } else {
             $title = $this->translator->trans($title, $options['translationParameters'], $options['translationDomain']);
         }
     }
     if (!isset($options['title'])) {
         $options['title'] = $title;
     }
     unset($options['absolute'], $options['translationDomain'], $options['translationParameters']);
     return array_merge($pagination->getPaginatorOptions(), $pagination->getCustomParameters(), compact('options', 'title', 'direction', 'sorted', 'key'));
 }
Exemple #26
0
 /**
  * {@inheritdoc}
  */
 public function addViolationAt($subPath, $message, array $params = array(), $invalidValue = null, $pluralization = null, $code = null)
 {
     $this->globalContext->getViolations()->add(new ConstraintViolation(
         null === $pluralization
             ? $this->translator->trans($message, $params, $this->translationDomain)
             : $this->translator->transChoice($message, $pluralization, $params, $this->translationDomain),
         $message,
         $params,
         $this->globalContext->getRoot(),
         $this->getPropertyPath($subPath),
         // check using func_num_args() to allow passing null values
         func_num_args() >= 4 ? $invalidValue : $this->value,
         $pluralization,
         $code
     ));
 }
Exemple #27
0
 /**
  * @param Container $container
  * @param ConstraintViolationListInterface $violations
  * @param array $controls
  */
 protected function mapViolationsToContainer(Container $container, ConstraintViolationListInterface $violations, array $controls = NULL)
 {
     foreach ($violations as $violation) {
         /** @var ConstraintViolationInterface $violation */
         $violation->getMessageTemplate();
         $message = $this->translator->transChoice($violation->getMessageTemplate(), $violation->getMessagePluralization(), $violation->getMessageParameters(), 'validators');
         $control = $this->findControl($container, $violation);
         if (($controls === NULL || in_array($control, $controls)) && (!$control instanceof Nette\Forms\IControl || count($control->getErrors()) === 0)) {
             if ($control instanceof Form) {
                 $control->addError('[' . $violation->getPropertyPath() . '] ' . $message);
             } else {
                 $control->addError($message);
             }
         }
     }
 }
Exemple #28
0
 /**
  * @param string $message
  * @param array  $values
  * @param null   $plural
  * @return string
  */
 protected function translate($message, array $values = array(), $plural = NULL)
 {
     $values['value'] = '%value';
     $values['name'] = '%name';
     $values['label'] = '%label';
     $parameters = array();
     foreach ($values as $name => $value) {
         if (!is_scalar($value)) {
             continue;
         }
         $parameters['{{ ' . $name . ' }}'] = $value;
     }
     if ($plural === NULL) {
         return $this->translator->trans($message, $parameters, 'validators');
     } else {
         return $this->translator->transChoice($message, $plural, $parameters, 'validators');
     }
 }
 /**
  * Show a report
  *
  * @param Request $request
  * @param int     $id
  *
  * @return \Symfony\Component\HttpFoundation\Response|JsonResponse
  */
 public function showAction(Request $request, $id)
 {
     $jobExecution = $this->jobExecutionRepo->find($id);
     if (null === $jobExecution) {
         throw new NotFoundHttpException('Akeneo\\Component\\Batch\\Model\\JobExecution entity not found');
     }
     $this->eventDispatcher->dispatch(JobExecutionEvents::PRE_SHOW, new GenericEvent($jobExecution));
     if ('json' === $request->getRequestFormat()) {
         $archives = [];
         foreach ($this->archivist->getArchives($jobExecution) as $key => $files) {
             $label = $this->translator->transChoice(sprintf('pim_import_export.download_archive.%s', $key), count($files));
             $archives[$key] = ['label' => ucfirst($label), 'files' => $files];
         }
         if (!$this->jobExecutionManager->checkRunningStatus($jobExecution)) {
             $this->jobExecutionManager->markAsFailed($jobExecution);
         }
         // limit the number of step execution returned to avoid memory overflow
         $context = ['limit_warnings' => 100];
         return new JsonResponse(['jobExecution' => $this->serializer->normalize($jobExecution, 'json', $context), 'hasLog' => file_exists($jobExecution->getLogFile()), 'archives' => $archives]);
     }
     return $this->templating->renderResponse(sprintf('PimImportExportBundle:%sExecution:show.html.twig', ucfirst($this->getJobType())), ['execution' => $jobExecution]);
 }
 /**
  * Get form validation errors.
  * @param Form| $form
  * @return array
  */
 protected function getAllFormErrorMessages($form)
 {
     // DEBUG
     //var_dump($form->getErrors($deep));
     //die();
     $messagesArray = array();
     foreach ($form->getErrors() as $key => $error) {
         if ($error->getMessagePluralization() !== null) {
             $messagesArray['message'] = $this->translator->transChoice($error->getMessage(), $error->getMessagePluralization(), $error->getMessageParameters(), 'validators');
         } else {
             $messagesArray['message'] = $this->translator->trans($error->getMessage(), array(), 'validators');
         }
     }
     // Children errors
     foreach ($form->all() as $name => $child) {
         $errors = $this->getAllFormErrorMessages($child);
         if (!empty($errors)) {
             $messagesArray[$name] = $errors;
         }
     }
     return $messagesArray;
 }