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());
 }
 /**
  * @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()]);
 }
 /**
  * {@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;
 }
 /**
  * @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);
     }
 }
 /**
  * @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;
 }
 /**
  * @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;
 }
 /**
  * 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());
     }
 }
 /**
  * @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;
 }
 /**
  * Set up the tests.
  */
 public function setUp()
 {
     parent::setUp();
     $this->translator = $this->app['translator'];
     $this->detector = new LanguageDetector($this->translator);
     $this->translator->setLocale('fr');
 }
 /**
  * {@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));
 }
 /**
  * {@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));
 }
 /**
  * @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');
     }
 }
 /**
  * {@inheritdoc}
  */
 public function visitMetadata(DatagridConfiguration $config, MetadataObject $data)
 {
     $currentViewId = $this->getCurrentViewId($config->getName());
     $this->setDefaultParams($config->getName());
     $data->offsetAddToArray('initialState', ['gridView' => self::DEFAULT_VIEW_ID]);
     $data->offsetAddToArray('state', ['gridView' => $currentViewId]);
     $allLabel = null;
     if (isset($config['options'], $config['options']['gridViews'], $config['options']['gridViews']['allLabel'])) {
         $allLabel = $this->translator->trans($config['options']['gridViews']['allLabel']);
     }
     /** @var AbstractViewsList $list */
     $list = $config->offsetGetOr(self::VIEWS_LIST_KEY, false);
     $systemGridView = new View(self::DEFAULT_VIEW_ID);
     $systemGridView->setDefault($this->getDefaultViewId($config->getName()) === null);
     $gridViews = ['choices' => [['label' => $allLabel, 'value' => self::DEFAULT_VIEW_ID]], 'views' => [$systemGridView->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->offsetAddToArray('gridViews', $gridViews);
 }
 /**
  * Returns an array with form fields errors
  *
  * @param FormInterface $form
  * @param bool|false $useLabels
  * @param array $errors
  * @return array
  */
 public function getErrorMessages(FormInterface $form, $useLabels = false, $errors = array())
 {
     if ($form->count() > 0) {
         foreach ($form->all() as $child) {
             if (!$child->isValid()) {
                 $errors = $this->getErrorMessages($child, $useLabels, $errors);
             }
         }
     }
     foreach ($form->getErrors() as $error) {
         if ($useLabels) {
             $fieldNameData = $this->getErrorFormLabel($form);
         } else {
             $fieldNameData = $this->getErrorFormId($form);
         }
         $fieldName = $fieldNameData;
         if ($useLabels) {
             /**
              * @ignore
              */
             $fieldName = $this->translator->trans($fieldNameData['label'], array(), $fieldNameData['domain']);
         }
         $errors[$fieldName] = $error->getMessage();
     }
     return $errors;
 }
Exemple #15
0
 /**
  * @param GridQueryDesignerInterface|AbstractQueryDesigner $value
  * @param QueryConstraint|Constraint                       $constraint
  */
 public function validate($value, Constraint $constraint)
 {
     if (!$value instanceof GridQueryDesignerInterface) {
         return;
     }
     $gridPrefix = $value->getGridPrefix();
     $builder = $this->getBuilder($gridPrefix);
     $builder->setGridName($gridPrefix);
     $builder->setSource($value);
     $message = $this->translator->trans($constraint->message);
     try {
         $dataGrid = $this->gridBuilder->build($builder->getConfiguration(), new ParameterBag());
         $dataSource = $dataGrid->getDatasource();
         if ($dataSource instanceof OrmDatasource) {
             $qb = $dataSource->getQueryBuilder();
             $qb->setMaxResults(1);
         }
         $dataSource->getResults();
     } catch (DBALException $e) {
         $this->context->addViolation($this->isDebug ? $e->getMessage() : $message);
     } catch (ORMException $e) {
         $this->context->addViolation($this->isDebug ? $e->getMessage() : $message);
     } catch (InvalidConfigurationException $e) {
         $this->context->addViolation($this->isDebug ? $e->getMessage() : $message);
     }
 }
 /**
  * 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;
 }
 /**
  * On success.
  *
  * @return RedirectResponse
  */
 public function onSuccess()
 {
     $alert = $this->alertManager->create();
     $alert->addSuccess($this->translator->trans('success.save_banner_zone', array(), 'SilvestraBanner'));
     $this->alertManager->setFlashAlert($alert);
     return new RedirectResponse($this->router->generate('silvestra_banner.banner_zone_list'));
 }
 /**
  * @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)]));
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $options['field_options_start'] = array_merge(array('label' => $this->translator->trans('date_range_start', array(), 'SonataCoreBundle')), $options['field_options_start']);
     $options['field_options_end'] = array_merge(array('label' => $this->translator->trans('date_range_end', array(), 'SonataCoreBundle')), $options['field_options_end']);
     $builder->add('start', $options['field_type'], array_merge(array('required' => false), $options['field_options'], $options['field_options_start']));
     $builder->add('end', $options['field_type'], array_merge(array('required' => false), $options['field_options'], $options['field_options_end']));
 }
Exemple #20
0
 /**
  * @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;
 }
 /**
  * @param \Symfony\Component\Form\Form $form
  * @param \AppBundle\Entity\User $user
  * @return bool
  */
 public function createUser(Form $form, User $user) : bool
 {
     $return = false;
     if (!$this->checkUsername($user->getUsername())) {
         $return = true;
         $form->get('username')->addError(new FormError($this->translator->trans('users.registration.username_already_taken')));
     }
     if (!$this->checkEmail($user->getEmail())) {
         $return = true;
         $form->get('email')->addError(new FormError($this->translator->trans('users.registration.email_already_taken')));
     }
     if ($return) {
         return false;
     }
     $user->setSalt(uniqid('', true));
     $password = $this->encoder->encodePassword($user, $user->getPlainPassword());
     $user->setPassword($password);
     $user->addRole('ROLE_USER');
     $user->enable(false);
     $this->em->persist($user);
     $this->em->flush();
     $this->activationLinkManager->createActivationLink($user);
     $this->activationLinkManager->sendValidationMail($user);
     return true;
 }
 /**
  * {@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);
 }
 /**
  * {@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);
     }
 }
 /**
  * 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;
 }
Exemple #25
0
 /**
  * @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;
 }
 /**
  * @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;
 }
 /**
  * @param ConfigureMenuEvent $event
  */
 public function onNavigationConfigure(ConfigureMenuEvent $event)
 {
     $menu = $event->getMenu();
     $children = array();
     $entitiesMenuItem = $menu->getChild('system_tab')->getChild('entities_list');
     if ($entitiesMenuItem) {
         /** @var ConfigProvider $entityConfigProvider */
         $entityConfigProvider = $this->configManager->getProvider('entity');
         /** @var ConfigProvider $entityExtendProvider */
         $entityExtendProvider = $this->configManager->getProvider('extend');
         $extendConfigs = $entityExtendProvider->getConfigs();
         foreach ($extendConfigs as $extendConfig) {
             if ($this->checkAvailability($extendConfig)) {
                 $config = $entityConfigProvider->getConfig($extendConfig->getId()->getClassname());
                 if (!class_exists($config->getId()->getClassName()) || !$this->securityFacade->hasLoggedUser() || !$this->securityFacade->isGranted('VIEW', 'entity:' . $config->getId()->getClassName())) {
                     continue;
                 }
                 $children[$config->get('label')] = array('label' => $this->translator->trans($config->get('label')), 'options' => array('route' => 'oro_entity_index', 'routeParameters' => array('entityName' => str_replace('\\', '_', $config->getId()->getClassName())), 'extras' => array('safe_label' => true, 'routes' => array('oro_entity_*'))));
             }
         }
         sort($children);
         foreach ($children as $child) {
             $entitiesMenuItem->addChild($child['label'], $child['options']);
         }
     }
 }
 /**
  * @param ScrollData $scrollData
  * @param string     $html
  */
 protected function addCategoryBlock(ScrollData $scrollData, $html)
 {
     $blockLabel = $this->translator->trans('orob2b.catalog.product.section.catalog');
     $blockId = $scrollData->addBlock($blockLabel);
     $subBlockId = $scrollData->addSubBlock($blockId);
     $scrollData->addSubBlockData($blockId, $subBlockId, $html);
 }
 /**
  * @param array $inputData
  * @param array $expectedData
  *
  * @dataProvider formatPriceTypeLabelsProvider
  */
 public function testFormatPriceTypeLabels(array $inputData, array $expectedData)
 {
     $this->translator->expects($this->any())->method('trans')->will($this->returnCallback(function ($type) {
         return $type;
     }));
     $this->assertSame($expectedData, $this->formatter->formatPriceTypeLabels($inputData));
 }
Exemple #30
-6
 /**
  * @param $fromEmail
  * @param BatchEntryMail $batchMail
  * @param $doSend
  */
 private function sendBatchMail($fromEmail, BatchEntryMail $batchMail, $doSend)
 {
     $receivers = $batchMail->getReceiverEntries($this->em);
     $this->writeOutput('Sending "' . $batchMail->getName() . '" mail to ' . count($receivers) . ' people from ' . $fromEmail);
     $spool = $this->mailer->getTransport()->getSpool();
     foreach ($receivers as $receiver) {
         try {
             $this->writeOutput(' -> ' . $receiver->getEmail());
             $htmlTemplate = $batchMail->getHtmlTemplate($receiver);
             $plainTextTemplate = $batchMail->getPlainTextTemplate($receiver);
             $templateData = $batchMail->getTemplateData($receiver, $this->em);
             $this->translator->setLocale($receiver->getPool()->getLocale());
             $plainTextBody = $this->twig->render($plainTextTemplate, $templateData);
             $htmlBody = $this->twig->render($htmlTemplate, $templateData);
             $message = \Swift_Message::newInstance()->setSubject($batchMail->getSubject($receiver, $this->translator))->setFrom($fromEmail, $batchMail->getFrom($receiver, $this->translator))->setTo($receiver->getEmail())->setBody($plainTextBody)->addPart($htmlBody, 'text/html');
             if ($doSend) {
                 $this->mailer->send($message);
                 $batchMail->handleMailSent($receiver, $this->em);
             }
         } catch (\Exception $e) {
             $this->writeOutput(sprintf('<error>An error occurred while sending mail for email "%s"</error>', $receiver->getEmail()));
             // mark as handled, as otherwise the system will keep retrying over and over again
             $batchMail->handleMailSent($receiver, $this->em);
         }
     }
     if ($doSend) {
         // only flush queue at the end of a batch
         $spool->flushQueue($this->transport);
     }
 }