Exemplo n.º 1
0
 /**
  * Creates the query builder used to get the results of the search query
  * performed by the user in the "search" view.
  *
  * @param array       $entityConfig
  * @param string      $searchQuery
  * @param string|null $sortField
  * @param string|null $sortDirection
  *
  * @return DoctrineQueryBuilder
  */
 public function createSearchQueryBuilder(array $entityConfig, $searchQuery, $sortField = null, $sortDirection = null)
 {
     /* @var EntityManager */
     $em = $this->doctrine->getManagerForClass($entityConfig['class']);
     /* @var DoctrineQueryBuilder */
     $queryBuilder = $em->createQueryBuilder()->select('entity')->from($entityConfig['class'], 'entity');
     $queryParameters = array();
     foreach ($entityConfig['search']['fields'] as $name => $metadata) {
         $isNumericField = in_array($metadata['dataType'], array('integer', 'number', 'smallint', 'bigint', 'decimal', 'float'));
         $isTextField = in_array($metadata['dataType'], array('string', 'text', 'guid'));
         if ($isNumericField && is_numeric($searchQuery)) {
             $queryBuilder->orWhere(sprintf('entity.%s = :exact_query', $name));
             // adding '0' turns the string into a numeric value
             $queryParameters['exact_query'] = 0 + $searchQuery;
         } elseif ($isTextField) {
             $searchQuery = strtolower($searchQuery);
             $queryBuilder->orWhere(sprintf('LOWER(entity.%s) LIKE :fuzzy_query', $name));
             $queryParameters['fuzzy_query'] = '%' . $searchQuery . '%';
             $queryBuilder->orWhere(sprintf('LOWER(entity.%s) IN (:words_query)', $name));
             $queryParameters['words_query'] = explode(' ', $searchQuery);
         }
     }
     if (0 !== count($queryParameters)) {
         $queryBuilder->setParameters($queryParameters);
     }
     if (null !== $sortField) {
         $queryBuilder->orderBy('entity.' . $sortField, $sortDirection ?: 'DESC');
     }
     return $queryBuilder;
 }
Exemplo n.º 2
0
 /**
  * @param LineItem $lineItem
  *
  * @return bool
  */
 public function process(LineItem $lineItem)
 {
     if (in_array($this->request->getMethod(), ['POST', 'PUT'], true)) {
         /** @var EntityManagerInterface $manager */
         $manager = $this->registry->getManagerForClass('OroB2BShoppingListBundle:LineItem');
         $manager->beginTransaction();
         // handle case for new shopping list creation
         $formName = $this->form->getName();
         $formData = $this->request->request->get($formName, []);
         if (empty($formData['shoppingList']) && !empty($formData['shoppingListLabel'])) {
             $shoppingList = $this->shoppingListManager->createCurrent($formData['shoppingListLabel']);
             $formData['shoppingList'] = $shoppingList->getId();
             $this->request->request->set($formName, $formData);
         }
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             /** @var LineItemRepository $lineItemRepository */
             $lineItemRepository = $manager->getRepository('OroB2BShoppingListBundle:LineItem');
             $existingLineItem = $lineItemRepository->findDuplicate($lineItem);
             if ($existingLineItem) {
                 $this->updateExistingLineItem($lineItem, $existingLineItem);
             } else {
                 $manager->persist($lineItem);
             }
             $manager->flush();
             $manager->commit();
             return true;
         } else {
             $manager->rollBack();
         }
     }
     return false;
 }
Exemplo n.º 3
0
 /**
  * @param GridView $entity
  */
 protected function onSuccess(GridView $entity)
 {
     $this->fixFilters($entity);
     $om = $this->registry->getManagerForClass('OroDataGridBundle:GridView');
     $om->persist($entity);
     $om->flush();
 }
 protected function setUp()
 {
     $this->initClient();
     $this->registry = $this->getContainer()->get('doctrine');
     $this->entityManager = $this->registry->getManagerForClass('OroWorkflowBundle:ProcessJob');
     $this->repository = $this->registry->getRepository('OroWorkflowBundle:ProcessJob');
     $this->loadFixtures(array('Oro\\Bundle\\WorkflowBundle\\Tests\\Functional\\DataFixtures\\LoadProcessEntities'));
 }
 /**
  * Looks for the object that corresponds to the selected 'id' of the current entity.
  *
  * @param array $entityConfig
  * @param mixed $itemId
  *
  * @return object The entity
  *
  * @throws EntityNotFoundException
  */
 private function findCurrentItem(array $entityConfig, $itemId)
 {
     $manager = $this->doctrine->getManagerForClass($entityConfig['class']);
     if (null === ($entity = $manager->getRepository($entityConfig['class'])->find($itemId))) {
         throw new EntityNotFoundException(array('entity' => $entityConfig, 'entity_id' => $itemId));
     }
     return $entity;
 }
Exemplo n.º 6
0
 /**
  * @param object $entity
  * @param string $type
  *
  * @return string
  */
 protected function getActivity($entity, $type)
 {
     $em = $this->registry->getManagerForClass(ActivityList::ENTITY_NAME);
     /** @var ActivityListRepository $repository */
     $repository = $em->getRepository(ActivityList::ENTITY_NAME);
     $count = $repository->getRecordsCountForTargetClassAndId(ClassUtils::getClass($entity), $entity->getId(), [$type]);
     return $count;
 }
Exemplo n.º 7
0
 /**
  * @param GridView $entity
  */
 protected function onSuccess(GridView $entity)
 {
     $default = $this->form->get('is_default')->getData();
     $this->setDefaultGridView($entity, $default);
     $this->fixFilters($entity);
     $om = $this->registry->getManagerForClass('OroDataGridBundle:GridView');
     $om->persist($entity);
     $om->flush();
 }
 protected function setUp()
 {
     $this->initClient();
     $this->getContainer()->get('akeneo_batch.job_repository')->getJobManager()->beginTransaction();
     $this->dropJobsRecords();
     $this->registry = $this->getContainer()->get('doctrine');
     $this->entityManager = $this->registry->getManagerForClass('OroWorkflowBundle:ProcessJob');
     $this->repository = $this->registry->getRepository('OroWorkflowBundle:ProcessJob');
     $this->loadFixtures(['Oro\\Bundle\\WorkflowBundle\\Tests\\Functional\\DataFixtures\\LoadProcessEntities']);
 }
Exemplo n.º 9
0
 /**
  * Returns a list of organization ids for which, current user has permission to update them.
  *
  * @return array
  */
 protected function getAuthorisedOrganizationIds()
 {
     /** @var EntityManager $manager */
     $manager = $this->doctrine->getManagerForClass('OroOrganizationBundle:Organization');
     $qb = $manager->createQueryBuilder();
     $qb->select('o.id')->from('OroOrganizationBundle:Organization', 'o');
     $query = $qb->getQuery();
     $query = $this->aclHelper->apply($query, 'EDIT');
     $result = $query->getArrayResult();
     $result = array_map('current', $result);
     return $result;
 }
 public function onChangePassword(ChangePasswordEvent $event)
 {
     $user = $event->getUser();
     $objectManager = $this->registry->getManagerForClass(get_class($user));
     if (isset($objectManager)) {
         $encoder = $this->encoderFactory->getEncoder($user);
         $password = $encoder->encodePassword($event->getPlainPassword(), $user->getSalt());
         $accessor = new PropertyAccessor();
         $accessor->setValue($user, 'password', $password);
         $objectManager->persist($user);
         $objectManager->flush();
     }
 }
Exemplo n.º 11
0
 /**
  * @param Registry $em
  * @param string $class
  */
 public function __construct(Registry $em, $class, Request $request)
 {
     $this->em = $em->getManagerForClass($class);
     $this->class = $class;
     $this->repository = $em->getRepository($class);
     $this->request = $request;
 }
Exemplo n.º 12
0
 /**
  * @param User     $user
  * @param GridView $gridView
  * @param bool     $default
  */
 public function setDefaultGridView(User $user, GridView $gridView, $default)
 {
     $isGridViewDefault = $gridView->getUsers()->contains($user);
     // Checks if default grid view changed
     if ($isGridViewDefault !== $default) {
         $om = $this->registry->getManagerForClass('OroDataGridBundle:GridView');
         /** @var GridViewRepository $repository */
         $repository = $om->getRepository('OroDataGridBundle:GridView');
         $gridViews = $repository->findDefaultGridViews($this->aclHelper, $user, $gridView, false);
         foreach ($gridViews as $view) {
             $view->removeUser($user);
         }
         if ($default) {
             $gridView->addUser($user);
         }
     }
 }
 public function load($key, array $options, DefinitionRegistry $registry)
 {
     $definition = new Definition($options['entity'], $this->doctrine->getManagerForClass($options['entity']));
     $definition->setTemplates($this->getTemplateDefinition($options['templates']));
     $definition->setObjectRetriever($options['object_retriever']);
     $definition->setController($options['controller']);
     $definition->setFlags(['create' => $options['create'], 'update' => $options['update'], 'delete' => $options['delete']]);
     $definition->setIndex($this->getIndexDefinition($key, $options));
     $definition->setForm($this->getFormDefinition($options['form'], $options['form_options_provider']));
     $definition->setName($key);
     if (null === $options['title']) {
         $definition->setEntityTitle(ucfirst(str_replace(['-', '_', '.'], ' ', $key)));
     } else {
         $definition->setEntityTitle($options['title']);
     }
     $definition->setExtras($options['extras']);
     $registry->addDefinition($definition, $key);
 }
 /**
  * @param ShoppingList $shoppingList
  *
  * @return bool
  */
 public function process(ShoppingList $shoppingList)
 {
     $this->form->setData($shoppingList);
     if (in_array($this->request->getMethod(), ['POST', 'PUT'], true)) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             if ($shoppingList->getId() === null) {
                 $this->manager->setCurrent($shoppingList->getAccountUser(), $shoppingList);
             } else {
                 $em = $this->doctrine->getManagerForClass('OroB2BShoppingListBundle:ShoppingList');
                 $em->persist($shoppingList);
                 $em->flush();
             }
             return true;
         }
     }
     return false;
 }
 /**
  * {@inheritdoc}
  */
 public function validate($entity, Constraint $constraint)
 {
     if (!$constraint instanceof TreeChoice) {
         throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\TreeParent');
     }
     $class = get_class($entity);
     $em = $this->registry->getManagerForClass($class);
     if (!$em) {
         throw new ConstraintDefinitionException(sprintf('Unable to find the object manager associated with an entity of class "%s".', $class));
     }
     $reader = new AnnotationReader();
     $metadata = $em->getClassMetadata($class);
     $properties = $metadata->getReflectionProperties();
     $idProperty = $metadata->getIdentifier();
     if (count($idProperty) > 1) {
         throw new ConstraintDefinitionException('Entity is not allowed to have more than one identifier field to be ' . 'part of a unique constraint in: ' . $metadata->getName());
     }
     $idProperty = $idProperty[0];
     $parentProperty = null;
     foreach ($properties as $property) {
         if ($reader->getPropertyAnnotation($property, static::PARENT_ANNOTATION)) {
             $parentProperty = $property->getName();
             break;
         }
     }
     if (null === $parentProperty) {
         throw new ConstraintDefinitionException('Neither of property of class: ' . $class . ' does not contain annotation:' . static::PARENT_ANNOTATION);
     }
     $parentEntity = $this->propertyAccessor->getValue($entity, $parentProperty);
     if (null === $parentEntity) {
         return;
     }
     if (!$parentEntity instanceof $class) {
         throw new ConstraintDefinitionException('Parent property value should be instance of: ' . $class . ' but given instance of: ' . get_class($parentEntity));
     }
     $entityId = $this->propertyAccessor->getValue($entity, $idProperty);
     $parentId = $this->propertyAccessor->getValue($parentEntity, $idProperty);
     if ($entityId === $parentId) {
         $this->context->buildViolation($constraint->message)->atPath($parentProperty)->addViolation();
     }
 }
Exemplo n.º 16
0
 /**
  * {@inheritdoc}
  */
 public function getRecipients(EmailRecipientsProviderArgs $args)
 {
     if (!$args->getRelatedEntity()) {
         return [];
     }
     $relatedEntity = $args->getRelatedEntity();
     $relatedEntityClass = ClassUtils::getClass($relatedEntity);
     $em = $this->registry->getManagerForClass($relatedEntityClass);
     $metadata = $em->getClassMetadata($relatedEntityClass);
     $idNames = $metadata->getIdentifierFieldNames();
     if (count($idNames) !== 1) {
         return [];
     }
     $propertyAccessor = PropertyAccess::createPropertyAccessor();
     $relatedEntityId = $propertyAccessor->getValue($relatedEntity, $idNames[0]);
     $recipients = [];
     $activities = $this->activityManager->getActivities($relatedEntityClass);
     $activityListQb = $this->createActivityListQb($relatedEntityClass, $relatedEntityId);
     $activityListDql = $activityListQb->getQuery()->getDQL();
     $limit = $args->getLimit();
     $activityKeys = array_keys($activities);
     foreach ($activityKeys as $class) {
         $qb = $this->getRepository($class)->createQueryBuilder('e');
         $qb->andWhere($qb->expr()->exists($activityListDql))->setParameter('related_activity_class', $class);
         foreach ($activityListQb->getParameters() as $param) {
             $qb->setParameter($param->getName(), $param->getValue(), $param->getType());
         }
         $iterator = new BufferedQueryResultIterator($qb);
         $iterator->setBufferSize($limit);
         foreach ($iterator as $entity) {
             $recipients = array_merge($recipients, EmailRecipientsHelper::filterRecipients($args, $this->relatedEmailsProvider->getRecipients($entity, 2, false, $args->getOrganization())));
             $limit -= count($recipients);
             if ($limit <= 0) {
                 break 2;
             }
         }
     }
     return $recipients;
 }
 /**
  * @param string $target
  * @param string[] $path
  * @param integer $entityId
  * @param integer $uniqueKey
  *
  * @return QueryBuilder
  */
 protected function getSubQuery($target, $path, $entityId, $uniqueKey)
 {
     $alias = 'inherit_' . $uniqueKey;
     $subQueryBuilder = $this->registry->getManagerForClass($target)->createQueryBuilder();
     $subQueryBuilder->select($alias . '.id')->from($target, $alias);
     foreach ($path as $key => $field) {
         $newAlias = 't_' . $uniqueKey . '_' . $key;
         $subQueryBuilder->join($alias . '.' . $field, $newAlias);
         $alias = $newAlias;
     }
     $subQueryBuilder->where($alias . '.id = :entityId')->setParameter('entityId', $entityId);
     return $subQueryBuilder;
 }
 /**
  * @param \FSi\Bundle\AdminSecurityBundle\Event\ChangePasswordEvent $event
  * @param \Doctrine\Bundle\DoctrineBundle\Registry $registry
  * @param \FSi\Bundle\AdminSecurityBundle\spec\fixtures\User $user
  * @param \Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface $encodeFactory
  * @param \Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface $encoder
  */
 function it_set_password_when_user_is_doctrine_entity($event, $registry, $user, $encodeFactory, $encoder)
 {
     $prophet = new Prophet();
     $em = $prophet->prophesize('Doctrine\\ORM\\EntityManager');
     $registry->getManagerForClass(Argument::type('string'))->willReturn($em);
     $event->getUser()->shouldBeCalled()->willReturn($user);
     $event->getPlainPassword()->shouldBeCalled()->willReturn('plain_password');
     $user->getSalt()->shouldBeCalled()->willReturn('salt');
     $encodeFactory->getEncoder($user)->shouldBeCalled()->willReturn($encoder);
     $encoder->encodePassword('plain_password', 'salt')->shouldBeCalled()->willReturn('encoded_password');
     $user->setPassword('encoded_password')->shouldBeCalled();
     $em->persist($user->getWrappedObject())->shouldBeCalled();
     $em->flush()->shouldBeCalled();
     $this->onChangePassword($event);
 }
Exemplo n.º 19
0
 /**
  * @param string $className
  *
  * @return ClassMetadata
  */
 protected function getMetadata($className)
 {
     $em = $this->registry->getManagerForClass($className);
     return $em->getClassMetadata($className);
 }
Exemplo n.º 20
0
 /**
  * @param Registry $registry
  * @param string $entityName
  */
 public function __construct(Registry $registry, $entityName)
 {
     $this->em = $registry->getManagerForClass($entityName);
     $this->repository = $registry->getRepository($entityName);
     $this->entityName = $entityName;
 }
 /**
  * @param string $class
  * @param mixed $id
  * @return object
  */
 protected function findObject($class, $id)
 {
     return $this->doctrine->getManagerForClass($class)->getReference($class, $id);
 }
 protected function getMetadatas($class)
 {
     // Cache is implemented by Doctrine itself
     return $this->doctrine->getManagerForClass($class)->getClassMetadata($class);
 }
Exemplo n.º 23
0
 /**
  * @param FormInterface $form
  * @param Request       $request
  * @param Registry      $registry
  */
 public function __construct(FormInterface $form, Request $request, Registry $registry)
 {
     $this->form = $form;
     $this->request = $request;
     $this->manager = $registry->getManagerForClass('OroB2BShoppingListBundle:LineItem');
 }
 public function __construct(DoctrineRegistry $registry)
 {
     $this->entityManager = $registry->getManagerForClass(self::ENTITY_CLASS);
     $this->repository = $registry->getRepository(self::ENTITY_CLASS);
 }
Exemplo n.º 25
0
 public function create($class_name, $property_name, \Symforce\AdminBundle\Compiler\Annotation\Form $annot, \Symforce\AdminBundle\Compiler\MetaType\PropertyContainer $parent, \Symforce\AdminBundle\Compiler\MetaType\Admin\Entity $entity = null)
 {
     $om = $this->doctrine->getManagerForClass($class_name);
     if (!$om) {
         throw new \Exception(sprintf("%s->%s has no orm", $class_name, $property_name));
     }
     $meta = $om->getClassMetadata($class_name);
     if (!$meta) {
         throw new \Exception(sprintf("%s->%s has no orm", $class_name, $property_name));
     }
     $map = null;
     if ($meta->hasAssociation($property_name)) {
         $map = $meta->getAssociationMapping($property_name);
     }
     $orm_type = $meta->getTypeOfField($property_name);
     $form_type = $annot->type;
     if ($entity) {
         if ($entity->class_name !== $class_name) {
             throw new \Exception(sprintf("%s->%s not match admin(%s) ", $class_name, $property_name, $entity->admin_name));
         }
     } else {
         if (!$this->gen->hasAdminClass($class_name)) {
             throw new \Exception(sprintf("%s->%s not find admin", $class_name, $property_name));
         }
         $entity = $this->gen->getAdminByClass($class_name);
     }
     if ($form_type) {
         if ('workflow' === $form_type) {
             if (!$entity->workflow) {
                 throw new \Exception(sprintf("%s->%s use form type:%s without define workflow", $class_name, $property_name, $form_type));
             } else {
                 if ($entity->workflow->property !== $property_name) {
                     throw new \Exception(sprintf("%s->%s use form type:%s, but workflow property is %s", $class_name, $property_name, $form_type, $entity->workflow->property));
                 }
             }
         }
         if ('owner' === $form_type) {
             if (!$entity->owner) {
                 throw new \Exception(sprintf("%s->%s use form type:%s without define owner", $class_name, $property_name, $form_type));
             } else {
                 if ($entity->owner->owner_property !== $property_name) {
                     throw new \Exception(sprintf("%s->%s use form type:%s, but owner property is %s", $class_name, $property_name, $form_type, $entity->owner->owner_property));
                 }
             }
         }
         if ($map) {
             if ($map['targetEntity'] !== $this->types[$form_type]['map'] && '*' !== $this->types[$form_type]['map']) {
                 if ($this->types[$form_type]['map']) {
                     throw new \Exception(sprintf("%s->%s use form type:%s with orm map type:%s, form type not accept orm map", $class_name, $property_name, $form_type, $map['targetEntity']));
                 } else {
                     throw new \Exception(sprintf("%s->%s use form type:%s with orm map type:%s, only accept orm map:(%s)", $class_name, $property_name, $form_type, $map['targetEntity'], $this->types[$form_type]['map']));
                 }
             }
         } else {
             if ($orm_type && !in_array($orm_type, $this->types[$form_type]['orm'])) {
                 throw new \Exception(sprintf("%s->%s use form type:%s with orm type:%s, only accept orm:(%s)", $class_name, $property_name, $form_type, $orm_type, join(',', $this->types[$form_type]['orm'])));
             }
         }
     } else {
         if ($entity->workflow && $entity->workflow->property === $property_name) {
             $form_type = 'workflow';
         } else {
             if ($entity->owner && $entity->owner->owner_property === $property_name) {
                 $form_type = 'owner';
             }
         }
         if (!$form_type) {
             if ($map) {
                 // $map['targetEntity']
                 foreach ($this->types as $_type_name => $_type) {
                     if ($map['targetEntity'] === $_type['map']) {
                         $form_type = $_type_name;
                         break;
                     }
                 }
                 if (!$form_type) {
                     // check if it is embed type
                     $cache = $this->gen->getAnnotationCache($class_name);
                     if (isset($cache->propertie_annotations[$property_name]['properties'])) {
                         $form_type = 'embed';
                     } else {
                         $form_type = 'entity';
                     }
                 }
             } else {
                 if ('string' === $orm_type) {
                     foreach ($this->guess as $keyword => $_type) {
                         if (false !== strpos($property_name, $keyword)) {
                             $form_type = $_type;
                             break;
                         }
                     }
                 } else {
                     if (isset($this->default_type[$orm_type])) {
                         $form_type = $this->default_type[$orm_type];
                     }
                     foreach ($this->types as $_type_name => $_type) {
                         if (!$_type['map'] && in_array($orm_type, $_type['orm'])) {
                             $form_type = $_type_name;
                             break;
                         }
                     }
                 }
                 if (!$form_type) {
                     $form_type = 'text';
                 }
             }
         }
     }
     if (!isset($this->types[$form_type]['class'])) {
         throw new \Exception(sprintf("%s->%s with form(%s) no class ", $class_name, $property_name, $form_type));
     }
     $form_class = $this->types[$form_type]['class'];
     /*
             if( !($form_class instanceof \Symforce\AdminBundle\Compiler\MetaType\Form\Element) ) {
                 throw new \Exception(sprintf("`%s` is invalid ", $form_class));
             }*/
     $form_element = new $form_class($parent, $entity, $property_name, $annot);
     $form_element->compile_meta_type = $form_type;
     $form_element->compile_form_type = $this->types[$form_type]['type'];
     $form_element->compile_orm_type = $orm_type;
     if ($meta->hasField($property_name)) {
         if ($meta->isUniqueField($property_name)) {
             if (null === $annot->unique) {
                 $form_element->unique = true;
             }
         }
     }
     if ($form_element->unique) {
         $cache = $this->gen->getAnnotationCache($class_name);
         if (isset($cache->propertie_annotations[$property_name])) {
             // $cache->propertie_annotations[$property_name]['Gedmo\Mapping\Annotation\Translatable']
             if (isset($cache->propertie_annotations[$property_name]['Gedmo\\Mapping\\Annotation\\Slug'])) {
                 if (null === $annot->unique) {
                     $form_element->unique = false;
                 }
                 if (null === $annot->required) {
                     $form_element->required = false;
                 }
             }
         }
     }
     return $form_element;
 }
 /**
  * @return EntityManager
  */
 protected function getAutoResponseRuleManager()
 {
     return $this->registry->getManagerForClass('Oro\\Bundle\\EmailBundle\\Entity\\AutoResponseRule');
 }
 /**
  * @param ContextAccessor $contextAccessor
  * @param Registry $registry
  */
 public function __construct(ContextAccessor $contextAccessor, Registry $registry)
 {
     $this->calendarRepository = $registry->getRepository('OroCalendarBundle:Calendar');
     $this->manager = $registry->getManagerForClass('Oro\\Bundle\\CalendarBundle\\Entity\\CalendarEvent');
     parent::__construct($contextAccessor);
 }
Exemplo n.º 28
0
 /**
  * @param Registry $registry
  * @param string $class
  */
 public function __construct(Registry $registry, $class)
 {
     $this->registry = $registry;
     $this->em = $registry->getManagerForClass($class);
     $this->class = $class;
 }