php Symfony-Component-Translation-TranslatorInterface类(方法)实例源码

下面列出了php Symfony-Component-Translation-TranslatorInterface 类(方法)源码代码实例,从而了解它的用法。

作者:bitbean    项目:laravel-language-detecto   
/**
  * Set up the tests.
  */
 public function setUp()
 {
     parent::setUp();
     $this->translator = $this->app['translator'];
     $this->detector = new LanguageDetector($this->translator);
     $this->translator->setLocale('fr');
 }

作者:startup    项目:platform-   
/**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->addEventSubscriber(new DecodeFolderSubscriber());
     $this->addOwnerOrganizationEventListener($builder);
     $this->addNewOriginCreateEventListener($builder);
     $this->addPrepopulateRefreshTokenEventListener($builder);
     $builder->addEventSubscriber(new OriginFolderSubscriber());
     $builder->addEventSubscriber(new ApplySyncSubscriber());
     $builder->add('check', 'button', ['label' => $this->translator->trans('oro.imap.configuration.connect'), 'attr' => ['class' => 'btn btn-primary']])->add('accessToken', 'hidden')->add('refreshToken', 'hidden')->add('accessTokenExpiresAt', 'hidden')->add('imapHost', 'hidden', ['required' => true, 'data' => GmailImap::DEFAULT_GMAIL_HOST])->add('imapPort', 'hidden', ['required' => true, 'data' => GmailImap::DEFAULT_GMAIL_PORT])->add('user', 'hidden', ['required' => true])->add('imapEncryption', 'hidden', ['required' => true, 'data' => GmailImap::DEFAULT_GMAIL_SSL])->add('clientId', 'hidden', ['data' => $this->userConfigManager->get('oro_google_integration.client_id')])->add('smtpHost', 'hidden', ['required' => false, 'data' => GmailImap::DEFAULT_GMAIL_SMTP_HOST])->add('smtpPort', 'hidden', ['required' => false, 'data' => GmailImap::DEFAULT_GMAIL_SMTP_PORT])->add('smtpEncryption', 'hidden', ['required' => false, 'data' => GmailImap::DEFAULT_GMAIL_SMTP_SSL]);
     $builder->get('accessTokenExpiresAt')->addModelTransformer(new CallbackTransformer(function ($originalAccessTokenExpiresAt) {
         if ($originalAccessTokenExpiresAt === null) {
             return '';
         }
         $now = new \DateTime('now', new \DateTimeZone('UTC'));
         return $originalAccessTokenExpiresAt->format('U') - $now->format('U');
     }, function ($submittedAccessTokenExpiresAt) {
         if ($submittedAccessTokenExpiresAt instanceof \DateTime) {
             return $submittedAccessTokenExpiresAt;
         }
         $utcTimeZone = new \DateTimeZone('UTC');
         $newExpireDate = new \DateTime('+' . (int) $submittedAccessTokenExpiresAt . ' seconds', $utcTimeZone);
         return $newExpireDate;
     }));
     $builder->addEventSubscriber(new GmailOAuthSubscriber($this->translator));
 }

作者:ramunas    项目:platfor   
/**
  * @param FormInterface $form
  * @param UserEmailOrigin $emailOrigin
  */
 protected function updateForm(FormInterface $form, UserEmailOrigin $emailOrigin)
 {
     if (!empty($emailOrigin->getAccessToken())) {
         $form->add('checkFolder', 'button', ['label' => $this->translator->trans('oro.email.retrieve_folders.label'), 'attr' => ['class' => 'btn btn-primary']])->add('folders', 'oro_email_email_folder_tree', ['label' => $this->translator->trans('oro.email.folders.label'), 'attr' => ['class' => 'folder-tree'], 'tooltip' => $this->translator->trans('oro.email.folders.tooltip')]);
         $form->remove('check');
     }
 }

作者:elibert    项目:api-bundl   
/**
  * @param object $object
  * @param null   $format
  * @param array  $context
  *
  * @return array|bool|float|int|null|string
  */
 public function normalize($object, $format = null, array $context = array())
 {
     if ($object instanceof \Exception) {
         $message = $object->getMessage();
         if ($this->debug) {
             $trace = $object->getTrace();
         }
     }
     $data = ['context' => 'Error', 'type' => 'Error', 'title' => isset($context['title']) ? $context['title'] : 'An error occurred', 'description' => isset($message) ? $message : (string) $object];
     if (isset($trace)) {
         $data['trace'] = $trace;
     }
     $msgError = $object->getMessage();
     if (method_exists($object, 'getErrors')) {
         $errors = [];
         foreach ($object->getErrors() as $key => $error) {
             foreach ($error as $name => $message) {
                 $errors[$key][$name] = $this->translator->trans($message);
             }
         }
         if (!empty($errors) && isset($data['description'])) {
             $data['description'] = ['title' => isset($msgError) ? $msgError : (string) $object, 'json-error' => $errors];
         }
     }
     return $data;
 }

作者:Maksol    项目:platfor   
/**
  * @param object|null $relatedEntity
  * @param string|null $query
  * @param Organization|null $organization
  * @param int $limit
  *
  * @return array
  */
 public function getEmailRecipients($relatedEntity = null, $query = null, Organization $organization = null, $limit = 100)
 {
     $emails = [];
     foreach ($this->providers as $provider) {
         if ($limit <= 0) {
             break;
         }
         $args = new EmailRecipientsProviderArgs($relatedEntity, $query, $limit, array_reduce($emails, 'array_merge', []), $organization);
         $recipients = $provider->getRecipients($args);
         if (!$recipients) {
             continue;
         }
         $limit = max([0, $limit - count($recipients)]);
         if (!array_key_exists($provider->getSection(), $emails)) {
             $emails[$provider->getSection()] = [];
         }
         $emails[$provider->getSection()] = array_merge($emails[$provider->getSection()], $recipients);
     }
     $result = [];
     foreach ($emails as $section => $sectionEmails) {
         $items = array_map(function (Recipient $recipient) {
             return $this->emailRecipientsHelper->createRecipientData($recipient);
         }, $sectionEmails);
         $result[] = ['text' => $this->translator->trans($section), 'children' => array_values($items)];
     }
     return $result;
 }

作者:ramunas    项目:platfor   
/**
  * @param AbstractQueryDesigner         $value
  * @param GroupingConstraint|Constraint $constraint
  */
 public function validate($value, Constraint $constraint)
 {
     $definition = json_decode($value->getDefinition(), true);
     if (empty($definition['columns'])) {
         return;
     }
     $columns = $definition['columns'];
     $aggregateColumns = array_filter($columns, function (array $column) {
         return !empty($column['func']);
     });
     if (empty($aggregateColumns)) {
         return;
     }
     $groupingColumns = [];
     if (!empty($definition['grouping_columns'])) {
         $groupingColumns = $definition['grouping_columns'];
     }
     $groupingColumnNames = ArrayUtil::arrayColumn($groupingColumns, 'name');
     $columnNames = ArrayUtil::arrayColumn($columns, 'name');
     $columnNamesToCheck = array_diff($columnNames, ArrayUtil::arrayColumn($aggregateColumns, 'name'));
     $columnsToGroup = array_diff($columnNamesToCheck, $groupingColumnNames);
     if (empty($columnsToGroup)) {
         return;
     }
     $columnLabels = [];
     foreach ($columns as $column) {
         if (in_array($column['name'], $columnsToGroup)) {
             $columnLabels[] = $column['label'];
         }
     }
     $this->context->addViolation($this->translator->trans($constraint->message, ['%columns%' => implode(', ', $columnLabels)]));
 }

作者:Maksol    项目:platfor   
/**
  * Process form
  *
  * @param  EmailTemplate $entity
  *
  * @return bool True on successful processing, false otherwise
  */
 public function process(EmailTemplate $entity)
 {
     // always use default locale during template edit in order to allow update of default locale
     $entity->setLocale($this->defaultLocale);
     if ($entity->getId()) {
         // refresh translations
         $this->manager->refresh($entity);
     }
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         // deny to modify system templates
         if ($entity->getIsSystem() && !$entity->getIsEditable()) {
             $this->form->addError(new FormError($this->translator->trans('oro.email.handler.attempt_save_system_template')));
             return false;
         }
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             // mark an email template creating by an user as editable
             if (!$entity->getId()) {
                 $entity->setIsEditable(true);
             }
             $this->manager->persist($entity);
             $this->manager->flush();
             return true;
         }
     }
     return false;
 }

作者:northdakot    项目:platfor   
/**
  * {@inheritDoc}
  */
 public function visitMetadata(DatagridConfiguration $config, MetadataObject $data)
 {
     $params = $this->getParameters()->get(ParameterBag::ADDITIONAL_PARAMETERS, []);
     $currentView = isset($params[self::VIEWS_PARAM_KEY]) ? $params[self::VIEWS_PARAM_KEY] : null;
     $data->offsetAddToArray('initialState', ['gridView' => '__all__']);
     $data->offsetAddToArray('state', ['gridView' => $currentView]);
     $allLabel = null;
     if (isset($config['options']) && isset($config['options']['gridViews']) && isset($config['options']['gridViews']['allLabel'])) {
         $allLabel = $this->translator->trans($config['options']['gridViews']['allLabel']);
     }
     /** @var AbstractViewsList $list */
     $list = $config->offsetGetOr(self::VIEWS_LIST_KEY, false);
     $gridViews = ['choices' => [['label' => $allLabel, 'value' => '__all__']], 'views' => [(new View('__all__'))->getMetadata()]];
     if ($list !== false) {
         $configuredGridViews = $list->getMetadata();
         $configuredGridViews['views'] = array_merge($gridViews['views'], $configuredGridViews['views']);
         $configuredGridViews['choices'] = array_merge($gridViews['choices'], $configuredGridViews['choices']);
         $gridViews = $configuredGridViews;
     }
     if ($this->eventDispatcher->hasListeners(GridViewsLoadEvent::EVENT_NAME)) {
         $event = new GridViewsLoadEvent($config->getName(), $gridViews);
         $this->eventDispatcher->dispatch(GridViewsLoadEvent::EVENT_NAME, $event);
         $gridViews = $event->getGridViews();
     }
     $gridViews['gridName'] = $config->getName();
     $gridViews['permissions'] = $this->getPermissions();
     $data->offsetSet('gridViews', $gridViews);
 }

作者:hasantayya    项目:oj   
/**
  * @param ResultSet $resultSet
  * @param $section
  * @return array
  */
 public function buildResultsObject(ResultSet $resultSet, $section)
 {
     $results = [];
     /**
      * @var Result $object
      */
     foreach ($resultSet as $object) {
         $objectType = $object->getType();
         if (!isset($results[$objectType])) {
             $results[$objectType]['data'] = [];
             $results[$objectType]['total_item'] = 1;
             $results[$objectType]['type'] = $this->translator->trans($object->getType());
         } else {
             $results[$objectType]['total_item']++;
         }
         if ($section == $objectType) {
             $result['detail'] = $this->getObjectDetail($object);
             $result['source'] = $object->getSource();
             if ($result['detail']['route']) {
                 $results[$objectType]['data'][] = $result;
             }
         }
     }
     //set only acceptable count for selected section
     if (!empty($section) && isset($results[$section])) {
         $results[$section]['total_item'] = count($results[$section]['data']);
     }
     foreach ($results as $result) {
         $this->setTotalHit($this->getTotalHit() + $result['total_item']);
     }
     return $results;
 }

作者:Maksol    项目:platfor   
/**
  * @param User $currentUser
  * @param GridView $gridView
  *
  * @return string
  */
 protected function createGridViewLabel(User $currentUser, GridView $gridView)
 {
     if ($gridView->getOwner()->getId() === $currentUser->getId()) {
         return $gridView->getName();
     }
     return $this->translator->trans('oro.datagrid.gridview.shared_by', ['%name%' => $gridView->getName(), '%owner%' => $gridView->getOwner()->getUsername()]);
 }

作者:Maksol    项目:platfor   
/**
  * Returns grouped search results
  *
  * @param string $string
  * @return array
  */
 public function getGroupedResults($string)
 {
     $search = $this->getResults($string);
     // empty key array contains all data
     $result = array('' => array('count' => 0, 'class' => '', 'config' => array(), 'icon' => '', 'label' => ''));
     /** @var $item Item */
     foreach ($search->getElements() as $item) {
         $config = $item->getEntityConfig();
         $alias = $config['alias'];
         if (!isset($result[$alias])) {
             $group = array('count' => 0, 'class' => $item->getEntityName(), 'config' => $config, 'icon' => '', 'label' => '');
             if (!empty($group['class']) && $this->configManager->hasConfig($group['class'])) {
                 $entityConfigId = new EntityConfigId('entity', $group['class']);
                 $entityConfig = $this->configManager->getConfig($entityConfigId);
                 if ($entityConfig->has('plural_label')) {
                     $group['label'] = $this->translator->trans($entityConfig->get('plural_label'));
                 }
                 if ($entityConfig->has('icon')) {
                     $group['icon'] = $entityConfig->get('icon');
                 }
             }
             $result[$alias] = $group;
         }
         $result[$alias]['count']++;
         $result['']['count']++;
     }
     uasort($result, function ($first, $second) {
         if ($first['label'] == $second['label']) {
             return 0;
         }
         return $first['label'] > $second['label'] ? 1 : -1;
     });
     return $result;
 }

作者:trustif    项目:oroplatform-mass-update-bundl   
/**
  * @param bool $withRelations
  *
  * @dataProvider testDataProvider
  */
 public function testBuildFormRegularGuesser($withRelations)
 {
     $entityName = 'Test\\Entity';
     $this->doctrineHelperMock->expects($this->once())->method('getEntityIdentifierFieldNames')->with($entityName)->willReturn(['id']);
     $fields = [['name' => 'oneField', 'type' => 'string', 'label' => 'One field'], ['name' => 'anotherField', 'type' => 'string', 'label' => 'Another field']];
     if ($withRelations) {
         $fields[] = ['name' => 'relField', 'relation_type' => 'ref-one', 'label' => 'Many to One field'];
     }
     $this->entityFieldMock->expects($this->once())->method('getFields')->willReturn($fields);
     $this->formConfigMock->expects($this->at(0))->method('getConfig')->with($entityName, 'oneField')->willReturn(new Config(new FieldConfigId('form', $entityName, 'someField'), ['is_enabled' => false]));
     $this->formConfigMock->expects($this->at(1))->method('getConfig')->with($entityName, 'anotherField')->willReturn(new Config(new FieldConfigId('form', $entityName, 'anotherField'), ['is_enabled' => true]));
     if ($withRelations) {
         $this->formConfigMock->expects($this->at(2))->method('getConfig')->with($entityName, 'relField')->willReturn(new Config(new FieldConfigId('form', $entityName, 'relField'), ['is_enabled' => true]));
         $this->translatorMock->expects($this->at(0))->method('trans')->with('oro.entity.form.entity_fields')->willReturn('Fields');
         $this->translatorMock->expects($this->at(1))->method('trans')->with('oro.entity.form.entity_related')->willReturn('Relations');
     }
     $form = $this->factory->create($this->type, null, ['entity' => $entityName, 'with_relations' => $withRelations]);
     $view = $form->createView();
     $this->assertEquals('update_field_choice', $view->vars['full_name'], 'Failed asserting that field name is correct');
     $this->assertNotEmpty($view->vars['configs']['component']);
     $this->assertEquals('entity-field-choice', $view->vars['configs']['component']);
     $this->assertEquals('update_field_choice', $form->getConfig()->getType()->getName(), 'Failed asserting that correct underlying type was used');
     if ($withRelations) {
         $this->assertCount(2, $view->vars['choices'], 'Failed asserting that choices are grouped');
     } else {
         $this->assertCount(1, $view->vars['choices'], 'Failed asserting that choices exists');
         /** @var ChoiceView $choice */
         $choice = reset($view->vars['choices']);
         $this->assertEquals('Another field', $choice->label);
     }
 }

作者:nathix8    项目:bcp-websit   
/**
  * {@inheritdoc}
  */
 public function shareList(array $posts)
 {
     $contacts = $this->contactProvider->getContacts();
     $now = new \DateTime();
     $from = $this->from;
     $subject = $this->getSubject($now);
     $response = array('sended' => false, 'errors' => array());
     foreach ($posts as $key => $post) {
         if (!$post->getPublished()) {
             $response['errors'][] = $this->translator->trans('newsletter_post_not_published', array('%post_title%' => $post->getTitle()), 'PostAdmin');
         }
     }
     if (empty($response['errors'])) {
         foreach ($contacts as $contact) {
             if (!$contact instanceof ContactInterface) {
                 throw new \InvalidArgumentException(sprintf("%s must implement %s.", get_class($contact), ContactInterface::class));
             }
             $template = $this->templating->render('@Admin/Batch/Newsletter/share_posts.html.twig', array('posts' => $posts, 'contact' => $contact));
             $to = array($contact->getEmail());
             if ($this->emailSender->send($from, $to, $subject, $template)) {
                 foreach ($posts as $post) {
                     $post->setSharedNewsletter($now);
                 }
                 $response['sended'] = true;
             }
         }
     }
     return $response;
 }

作者:szymac    项目:admin-translatable-bundl   
/**
  * @return Item
  */
 private function createRootItem()
 {
     $translation = new Item('translation-locale');
     $translation->setLabel($this->translator->trans('admin.locale.dropdown.title', array('%locale%' => $this->localeManager->getLocale()), 'FSiAdminTranslatableBundle'));
     $translation->setOptions(array('attr' => array('id' => 'translatable-switcher')));
     return $translation;
 }

作者:szymac    项目:admin-security-bundl   
/**
  * @return Item
  */
 private function createRootItem()
 {
     $rootItem = new Item('account');
     $rootItem->setLabel($this->translator->trans('admin.welcome', array('%username%' => $this->tokenStorage->getToken()->getUsername()), 'FSiAdminSecurity'));
     $rootItem->setOptions(array('attr' => array('id' => 'account')));
     return $rootItem;
 }

作者:nk    项目:translate-bundl   
/**
  * 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());
     }
 }

作者:nass5    项目:La   
/**
  * @param FormInterface     $form
  * @param array             $results
  *
  * @return array
  */
 private function formatFormErrors(FormInterface $form, &$results = array())
 {
     /*
      * first check if there are any errors bound for this element
      */
     $errors = $form->getErrors();
     if (count($errors)) {
         $messages = [];
         foreach ($errors as $error) {
             if ($error instanceof FormError) {
                 $messages[] = $this->translator->trans($error->getMessage(), $error->getMessageParameters(), 'validators');
             }
             $results[] = ['property_path' => $this->formatPropertyPath($error), 'message' => join(', ', $messages)];
         }
     }
     /*
      * Then, check if there are any children. If yes, then parse them
      */
     $children = $form->all();
     if (count($children)) {
         foreach ($children as $child) {
             if ($child instanceof FormInterface) {
                 $this->formatFormErrors($child, $results);
             }
         }
     }
     return $results;
 }

作者:hafeez300    项目:orocommerc   
/**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     if ($options['em'] === null) {
         $em = $this->registry->getManagerForClass($options['class']);
     } else {
         $em = $this->registry->getManager($options['em']);
     }
     $repository = $em->getRepository($options['class']);
     $entities = $repository->findAll();
     /** @var ClassMetadataInfo $classMetadata */
     $classMetadata = $em->getClassMetadata($options['class']);
     $identifierField = $classMetadata->getSingleIdentifierFieldName();
     $choiceLabels = [];
     /** @var AddressType $entity */
     foreach ($entities as $entity) {
         $pkValue = $classMetadata->getReflectionProperty($identifierField)->getValue($entity);
         if ($options['property']) {
             $value = $classMetadata->getReflectionProperty($options['property'])->getValue($entity);
         } else {
             $value = (string) $entity;
         }
         $choiceLabels[$pkValue] = $this->translator->trans('orob2b.customer.customer_typed_address_with_default_type.choice.default_text', ['%type_name%' => $value]);
     }
     $builder->add('default', 'choice', ['choices' => $choiceLabels, 'multiple' => true, 'expanded' => true, 'label' => false])->addViewTransformer(new AddressTypeDefaultTransformer($em));
 }

作者:ramunas    项目:platfor   
/**
  * {@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);
     }
 }

作者:adam-paterso    项目:orocommerc   
public function testGetSubtotals()
 {
     $this->translator->expects($this->once())->method('trans')->with(sprintf('orob2b.order.subtotals.%s', Subtotal::TYPE_SUBTOTAL))->willReturn(ucfirst(Subtotal::TYPE_SUBTOTAL));
     $order = new Order();
     $perUnitLineItem = new OrderLineItem();
     $perUnitLineItem->setPriceType(OrderLineItem::PRICE_TYPE_UNIT);
     $perUnitLineItem->setPrice(Price::create(20, 'USD'));
     $perUnitLineItem->setQuantity(2);
     $bundledUnitLineItem = new OrderLineItem();
     $bundledUnitLineItem->setPriceType(OrderLineItem::PRICE_TYPE_BUNDLED);
     $bundledUnitLineItem->setPrice(Price::create(2, 'USD'));
     $bundledUnitLineItem->setQuantity(10);
     $otherCurrencyLineItem = new OrderLineItem();
     $otherCurrencyLineItem->setPriceType(OrderLineItem::PRICE_TYPE_UNIT);
     $otherCurrencyLineItem->setPrice(Price::create(10, 'EUR'));
     $otherCurrencyLineItem->setQuantity(10);
     $emptyLineItem = new OrderLineItem();
     $order->addLineItem($perUnitLineItem);
     $order->addLineItem($bundledUnitLineItem);
     $order->addLineItem($emptyLineItem);
     $order->addLineItem($otherCurrencyLineItem);
     $order->setCurrency('USD');
     $subtotals = $this->provider->getSubtotals($order);
     $this->assertInstanceOf('Doctrine\\Common\\Collections\\ArrayCollection', $subtotals);
     $subtotal = $subtotals->get(Subtotal::TYPE_SUBTOTAL);
     $this->assertInstanceOf('OroB2B\\Bundle\\OrderBundle\\Model\\Subtotal', $subtotal);
     $this->assertEquals(Subtotal::TYPE_SUBTOTAL, $subtotal->getType());
     $this->assertEquals(ucfirst(Subtotal::TYPE_SUBTOTAL), $subtotal->getLabel());
     $this->assertEquals($order->getCurrency(), $subtotal->getCurrency());
     $this->assertInternalType('float', $subtotal->getAmount());
     $this->assertEquals(142.0, $subtotal->getAmount());
 }


问题


面经


文章

微信
公众号

扫码关注公众号