Exemple #1
0
 /**
  * @param object $entity
  * @return object|null
  */
 public function discoverSimilar($entity)
 {
     if (!$this->configuration) {
         return null;
     }
     $idName = $this->doctrineHelper->getSingleEntityIdentifierFieldName($this->discoveryEntityClass);
     $idFieldName = self::ROOT_ALIAS . '.' . $idName;
     /** @var EntityRepository $repository */
     $repository = $this->doctrineHelper->getEntityRepository($this->discoveryEntityClass);
     $qb = $repository->createQueryBuilder(self::ROOT_ALIAS)->select(self::ROOT_ALIAS);
     // Apply search strategies
     $this->applyStrategies($qb, $entity);
     // Apply matcher strategy
     if ($this->configuration[Configuration::DISCOVERY_OPTIONS_KEY][Configuration::DISCOVERY_MATCH_KEY] === Configuration::DISCOVERY_MATCH_LATEST) {
         $qb->orderBy($idFieldName, Criteria::DESC);
     }
     // Skip current entity
     $id = $this->doctrineHelper->getSingleEntityIdentifier($entity);
     if (!empty($id)) {
         $idParameter = ':' . $idName;
         $qb->andWhere($qb->expr()->neq($idFieldName, $idParameter))->setParameter($idParameter, $id);
     }
     // Add organization limits
     $organizationField = $this->ownershipMetadata->getMetadata(ClassUtils::getClass($entity))->getOrganizationFieldName();
     if ($organizationField) {
         $propertyAccessor = PropertyAccess::createPropertyAccessor();
         $organization = $propertyAccessor->getValue($entity, $organizationField);
         $qb->andWhere(sprintf('%s.%s = :organization', self::ROOT_ALIAS, $organizationField))->setParameter('organization', $organization);
     }
     // Get only 1 match
     $qb->setMaxResults(1);
     return $qb->getQuery()->getOneOrNullResult();
 }
Exemple #2
0
 /**
  * {@inheritdoc}
  */
 public function merge(FieldData $fieldData)
 {
     $entityData = $fieldData->getEntityData();
     $masterEntity = $entityData->getMasterEntity();
     $sourceEntity = $fieldData->getSourceEntity();
     if ($masterEntity->getId() !== $sourceEntity->getId()) {
         $queryBuilder = $this->doctrineHelper->getEntityRepository('OroNoteBundle:Note')->getBaseAssociatedNotesQB(ClassUtils::getRealClass($masterEntity), $masterEntity->getId());
         $notes = $queryBuilder->getQuery()->getResult();
         if (!empty($notes)) {
             $entityManager = $this->doctrineHelper->getEntityManager(current($notes));
             foreach ($notes as $note) {
                 $entityManager->remove($note);
             }
         }
         $queryBuilder = $this->doctrineHelper->getEntityRepository('OroNoteBundle:Note')->getBaseAssociatedNotesQB(ClassUtils::getRealClass($masterEntity), $sourceEntity->getId());
         $notes = $queryBuilder->getQuery()->getResult();
         if (!empty($notes)) {
             foreach ($notes as $note) {
                 $note->setTarget($masterEntity);
             }
         }
         $fieldMetadata = $fieldData->getMetadata();
         $activityClass = $fieldMetadata->get('type');
         $entityClass = ClassUtils::getRealClass($sourceEntity);
         $queryBuilder = $this->doctrineHelper->getEntityRepository(ActivityList::ENTITY_NAME)->getActivityListQueryBuilderByActivityClass($entityClass, $sourceEntity->getId(), $activityClass);
         $activityListItems = $queryBuilder->getQuery()->getResult();
         $activityIds = ArrayUtils::arrayColumn($activityListItems, 'id');
         $this->activityListManager->replaceActivityTargetWithPlainQuery($activityIds, $entityClass, $sourceEntity->getId(), $masterEntity->getId());
     }
 }
 /**
  * @param string $entityName
  * @param array $criteria
  * @return object|null
  */
 public function findOneBy($entityName, array $criteria)
 {
     $serializationCriteria = [];
     $where = [];
     foreach ($criteria as $field => $value) {
         if (is_object($value)) {
             $serializationCriteria[$field] = $this->getIdentifier($value);
         } else {
             $serializationCriteria[$field] = $value;
         }
         $where[] = sprintf('e.%s = :%s', $field, $field);
     }
     $storageKey = $this->getStorageKey($serializationCriteria);
     if (empty($this->entities[$entityName]) || empty($this->entities[$entityName][$storageKey])) {
         /** @var EntityRepository $entityRepository */
         $entityRepository = $this->doctrineHelper->getEntityRepository($entityName);
         $queryBuilder = $entityRepository->createQueryBuilder('e')->andWhere(implode(' AND ', $where))->setParameters($criteria)->setMaxResults(1);
         if ($this->shouldBeAddedOrganizationLimits($entityName)) {
             $ownershipMetadataProvider = $this->ownershipMetadataProviderLink->getService();
             $organizationField = $ownershipMetadataProvider->getMetadata($entityName)->getOrganizationFieldName();
             $queryBuilder->andWhere('e.' . $organizationField . ' = :organization')->setParameter('organization', $this->securityFacadeLink->getService()->getOrganization());
         }
         $this->entities[$entityName][$storageKey] = $queryBuilder->getQuery()->getOneOrNullResult();
     }
     return $this->entities[$entityName][$storageKey];
 }
 /**
  * {@inheritdoc}
  */
 public function getCalendarEvents($organizationId, $userId, $calendarId, $start, $end, $connections, $extraFields = [])
 {
     if (!$this->calendarConfig->isSystemCalendarEnabled() || !$this->securityFacade->isGranted('oro_system_calendar_view')) {
         return [];
     }
     //@TODO: temporary return all system calendars until BAP-6566 implemented
     ///** @var CalendarEventRepository $repo */
     //$repo = $this->doctrineHelper->getEntityRepository('OroCalendarBundle:CalendarEvent');
     //$qb = $repo->getSystemEventListByTimeIntervalQueryBuilder(
     //    $calendarId,
     //    $start,
     //    $end,
     //    []
     //);
     /** @var CalendarEventRepository $repo */
     $repo = $this->doctrineHelper->getEntityRepository('OroCalendarBundle:CalendarEvent');
     $qb = $repo->getSystemEventListByTimeIntervalQueryBuilder($start, $end, [], $extraFields)->andWhere('c.organization = :organizationId')->setParameter('organizationId', $organizationId);
     $invisibleIds = [];
     foreach ($connections as $id => $visible) {
         if (!$visible) {
             $invisibleIds[] = $id;
         }
     }
     if (!empty($invisibleIds)) {
         $qb->andWhere('c.id NOT IN (:invisibleIds)')->setParameter('invisibleIds', $invisibleIds);
     }
     return $this->calendarEventNormalizer->getCalendarEvents($calendarId, $qb->getQuery());
 }
 /**
  * {@inheritdoc}
  */
 protected function applyAdditionalData(&$items, $calendarId)
 {
     $parentEventIds = $this->getParentEventIds($items);
     if (!empty($parentEventIds)) {
         /** @var CalendarEventRepository $repo */
         $repo = $this->doctrineHelper->getEntityRepository('OroCalendarBundle:CalendarEvent');
         $invitees = $repo->getInvitedUsersByParentsQueryBuilder($parentEventIds)->getQuery()->getArrayResult();
         $groupedInvitees = [];
         foreach ($invitees as $invitee) {
             $groupedInvitees[$invitee['parentEventId']][] = $invitee;
         }
         foreach ($items as &$item) {
             $item['invitedUsers'] = [];
             if (isset($groupedInvitees[$item['id']])) {
                 foreach ($groupedInvitees[$item['id']] as $invitee) {
                     $item['invitedUsers'][] = $invitee['userId'];
                 }
             }
         }
     } else {
         foreach ($items as &$item) {
             $item['invitedUsers'] = [];
         }
     }
 }
 /**
  * @param OrmResultAfter $event
  */
 public function onResultAfter(OrmResultAfter $event)
 {
     $currencies = $this->getCurrencies();
     if (!$currencies) {
         return;
     }
     /** @var ResultRecord[] $records */
     $records = $event->getRecords();
     $productIds = [];
     foreach ($records as $record) {
         $productIds[] = $record->getValue('id');
     }
     /** @var ProductPriceRepository $priceRepository */
     $priceRepository = $this->doctrineHelper->getEntityRepository('OroB2BPricingBundle:ProductPrice');
     $priceList = $this->getPriceList();
     $showTierPrices = $this->priceListRequestHandler->getShowTierPrices();
     $prices = $priceRepository->findByPriceListIdAndProductIds($priceList->getId(), $productIds, $showTierPrices);
     $groupedPrices = $this->groupPrices($prices);
     foreach ($records as $record) {
         $record->addData(['showTierPrices' => $showTierPrices]);
         $productId = $record->getValue('id');
         $priceContainer = [];
         foreach ($currencies as $currencyIsoCode) {
             $columnName = $this->buildColumnName($currencyIsoCode);
             if (isset($groupedPrices[$productId][$currencyIsoCode])) {
                 $priceContainer[$columnName] = $groupedPrices[$productId][$currencyIsoCode];
             } else {
                 $priceContainer[$columnName] = [];
             }
         }
         if ($priceContainer) {
             $record->addData($priceContainer);
         }
     }
 }
Exemple #7
0
 /**
  * @param string $args
  * @param array $states
  *
  * @return Job[]
  */
 public function getJob($args = null, array $states = [])
 {
     $qb = $this->doctrineHelper->getEntityRepository('JMSJobQueueBundle:Job')->createQueryBuilder('j');
     $qb->where($qb->expr()->andX($qb->expr()->eq('j.command', ':command'), $qb->expr()->in('j.state', ':states')))->setParameters(['command' => CalculateAnalyticsCommand::COMMAND_NAME, 'states' => $states ?: [Job::STATE_PENDING]]);
     if ($args) {
         $qb->andWhere($qb->expr()->like('cast(j.args as text)', ':args'))->setParameter('args', '%' . $args . '%');
     } else {
         $qb->andWhere($qb->expr()->notLike('cast(j.args as text)', ':args'))->setParameter('args', '%--channel%');
     }
     return $qb->getQuery()->getResult();
 }
 /**
  * @param string $enumClass = ExtendHelper::buildEnumValueClassName($enumCode);
  * @return array
  */
 public function getEnumChoices($enumClass)
 {
     /** @var EnumValueRepository $repository */
     $repository = $this->doctrineHelper->getEntityRepository($enumClass);
     $values = $repository->getValues();
     $result = [];
     /** @var AbstractEnumValue $enum */
     foreach ($values as $enum) {
         $result[$enum->getId()] = $enum->getName();
     }
     return $result;
 }
 /**
  * @param string $className
  * @return bool
  */
 public function hasMarketingList($className)
 {
     if (null === $this->marketingListByEntity) {
         $this->marketingListByEntity = [];
         $repository = $this->doctrineHelper->getEntityRepository('OroCRMMarketingListBundle:MarketingList');
         $qb = $repository->createQueryBuilder('ml')->select('ml.entity')->distinct(true);
         $entities = $qb->getQuery()->getArrayResult();
         foreach ($entities as $entity) {
             $this->marketingListByEntity[$entity['entity']] = true;
         }
     }
     return !empty($this->marketingListByEntity[$className]);
 }
Exemple #10
0
 /**
  * {@inheritdoc}
  */
 public function getRemoveAceQueryBuilder(AclClass $aclClass, array $removeScopes)
 {
     $qb = $this->doctrineHelper->getEntityRepository('OroSecurityBundle:AclEntry')->createQueryBuilder('ae')->delete();
     $qb->where('ae.class = :class');
     $qbSub = $this->doctrineHelper->getEntityRepository('OroSecurityBundle:AclSecurityIdentity')->createQueryBuilder('asid')->select('asid.id');
     $exprOr = $qbSub->expr()->orX();
     foreach ($removeScopes as $scope) {
         $this->addExprByShareScope($qbSub, $exprOr, $scope);
     }
     $qbSub->where($exprOr);
     $qb->andWhere($qb->expr()->in('ae.securityIdentity', $qbSub->getDQL()))->setParameter('class', $aclClass);
     return $qb;
 }
 /**
  * {@inheritdoc}
  */
 public function getCalendarEvents($organizationId, $userId, $calendarId, $start, $end, $connections, $extraFields = [])
 {
     if (!$this->myTasksEnabled) {
         return [];
     }
     if ($this->isCalendarVisible($connections, self::MY_TASKS_CALENDAR_ID)) {
         /** @var TaskRepository $repo */
         $repo = $this->doctrineHelper->getEntityRepository('OroCRMTaskBundle:Task');
         $qb = $repo->getTaskListByTimeIntervalQueryBuilder($userId, $start, $end, $extraFields);
         $query = $this->aclHelper->apply($qb);
         return $this->taskCalendarNormalizer->getTasks(self::MY_TASKS_CALENDAR_ID, $query);
     }
     return [];
 }
 /**
  * @param BeforeListRenderEvent $event
  */
 public function onProductView(BeforeListRenderEvent $event)
 {
     if (!$this->request) {
         return;
     }
     $productId = $this->request->get('id');
     /** @var Product $product */
     $product = $this->doctrineHelper->getEntityReference('OroB2BProductBundle:Product', $productId);
     /** @var CategoryRepository $repository */
     $repository = $this->doctrineHelper->getEntityRepository('OroB2BCatalogBundle:Category');
     $category = $repository->findOneByProduct($product);
     $template = $event->getEnvironment()->render('OroB2BCatalogBundle:Product:category_view.html.twig', ['entity' => $category]);
     $this->addCategoryBlock($event->getScrollData(), $template);
 }
 public function testGetEntityRepositoryNotManageableEntity()
 {
     $class = 'ItemStubProxy';
     $this->setExpectedException('Oro\\Bundle\\EntityBundle\\Exception\\NotManageableEntityException', sprintf('Entity class "%s" is not manageable', $class));
     $this->registry->expects($this->once())->method('getManagerForClass')->with($class)->will($this->returnValue(null));
     $this->doctrineHelper->getEntityRepository($class);
 }
 /**
  * @return ProductRepository
  */
 protected function getProductRepository()
 {
     if (!$this->productRepository) {
         $this->productRepository = $this->doctrineHelper->getEntityRepository($this->productClass);
     }
     return $this->productRepository;
 }
Exemple #15
0
 /**
  * @param int $channelId
  * @param string $type
  *
  * @return RFMMetricCategory[]
  */
 protected function getCategories($channelId, $type)
 {
     if (array_key_exists($channelId, $this->categories) && array_key_exists($type, $this->categories[$channelId])) {
         return $this->categories[$channelId][$type];
     }
     $categories = $this->doctrineHelper->getEntityRepository('OroCRMAnalyticsBundle:RFMMetricCategory')->findBy(['channel' => $channelId, 'categoryType' => $type], ['categoryIndex' => Criteria::ASC]);
     $this->categories[$channelId][$type] = $categories;
     return $categories;
 }
 /**
  * {@inheritdoc}
  */
 public function getCalendarEvents($organizationId, $userId, $calendarId, $start, $end, $connections, $extraFields = [])
 {
     /** @var CalendarEventRepository $repo */
     $repo = $this->doctrineHelper->getEntityRepository('OroCalendarBundle:CalendarEvent');
     $qb = $repo->getUserEventListByTimeIntervalQueryBuilder($start, $end, [], $extraFields);
     $visibleIds = [];
     foreach ($connections as $id => $visible) {
         if ($visible) {
             $visibleIds[] = $id;
         }
     }
     if (!empty($visibleIds)) {
         $qb->andWhere('c.id IN (:visibleIds)')->setParameter('visibleIds', $visibleIds);
     } else {
         $qb->andWhere('1 = 0');
     }
     return $this->calendarEventNormalizer->getCalendarEvents($calendarId, $qb->getQuery());
 }
Exemple #17
0
 /**
  * Loads title templates from a database and if they are not found there gets them from a config.
  *
  * @param string $routeName
  *
  * @return array ['title' => title template, 'short_title' => short title template]
  *               also empty array may be returned if a route has no configured title
  *
  * @throws \RuntimeException if the given route has no title templates
  */
 public function getTitleTemplates($routeName)
 {
     if (isset($this->cache[$routeName])) {
         return $this->cache[$routeName];
     }
     /** @var Title $title */
     $title = $this->doctrineHelper->getEntityRepository('Oro\\Bundle\\NavigationBundle\\Entity\\Title')->findOneBy(['route' => $routeName]);
     if ($title) {
         $result = ['title' => $title->getTitle(), 'short_title' => $title->getShortTitle()];
     } else {
         if (isset($this->titles[$routeName])) {
             $result = ['title' => $this->titles[$routeName], 'short_title' => $this->titles[$routeName]];
         } else {
             $result = [];
         }
     }
     $this->cache[$routeName] = $result;
     return $result;
 }
Exemple #18
0
 /**
  * {@inheritdoc}
  */
 public function merge(FieldData $fieldData)
 {
     $entityData = $fieldData->getEntityData();
     $masterEntity = $entityData->getMasterEntity();
     $fieldMetadata = $fieldData->getMetadata();
     $entities = $fieldData->getEntityData()->getEntities();
     foreach ($entities as $sourceEntity) {
         if ($sourceEntity->getId() !== $masterEntity->getId()) {
             $entityClass = ClassUtils::getRealClass($masterEntity);
             $activityClass = $fieldMetadata->get('type');
             $queryBuilder = $this->doctrineHelper->getEntityRepository(ActivityList::ENTITY_NAME)->getActivityListQueryBuilderByActivityClass($entityClass, $sourceEntity->getId(), $activityClass);
             $activityListItems = $queryBuilder->getQuery()->getResult();
             $activityIds = ArrayUtils::arrayColumn($activityListItems, 'id');
             $this->activityListManager->replaceActivityTargetWithPlainQuery($activityIds, $entityClass, $sourceEntity->getId(), $masterEntity->getId());
             $activityIds = ArrayUtils::arrayColumn($activityListItems, 'relatedActivityId');
             $this->activityListManager->replaceActivityTargetWithPlainQuery($activityIds, $entityClass, $sourceEntity->getId(), $masterEntity->getId(), $activityClass);
         }
     }
 }
 /**
  * @param int $channelId
  * @return Channel
  */
 protected function getChannelById($channelId)
 {
     $this->validateChannelId($channelId);
     if (empty($this->channels[$channelId])) {
         /** @var Channel $channel */
         $channel = $this->doctrineHelper->getEntityRepository($this->channelClassName)->find($channelId);
         if (!$channel) {
             throw new \InvalidArgumentException(sprintf('Channel with id "%s" not found', $channelId));
         }
         $this->channels[$channelId] = $channel;
     }
     return $this->channels[$channelId];
 }
Exemple #20
0
 /**
  * @param FormEvent $event
  */
 public function loadCategories(FormEvent $event)
 {
     /** @var Channel $channel */
     $channel = $event->getData();
     if (!$this->isApplicable($channel)) {
         return;
     }
     $categories = $this->doctrineHelper->getEntityRepository($this->rfmCategoryClass)->findBy(['channel' => $channel], ['categoryIndex' => Criteria::ASC]);
     $channelData = (array) $channel->getData();
     $rfmEnabled = !empty($channelData[RFMAwareInterface::RFM_STATE_KEY]);
     $form = $event->getForm();
     $form->add(RFMAwareInterface::RFM_STATE_KEY, 'checkbox', ['label' => 'orocrm.analytics.form.rfm_enable.label', 'mapped' => false, 'required' => false, 'data' => $rfmEnabled, 'tooltip' => 'orocrm.analytics.rfm.tooltip']);
     $this->addRFMTypes($form, $categories);
 }
 /**
  * Gets a default option of an enum associated with the given field
  * This method must be public because it is used as a callback
  *
  * @param string $fieldName
  *
  * @return string|null
  */
 public function getEnumDefaultValue($fieldName)
 {
     if (isset($this->computedDefaultValues[$fieldName]) || array_key_exists($fieldName, $this->computedDefaultValues)) {
         return $this->computedDefaultValues[$fieldName];
     }
     $fieldConfig = $this->configManager->getConfig(new FieldConfigId('extend', self::CALENDAR_PROPERTY_CLASS, $fieldName, 'enum'));
     $repo = $this->doctrineHelper->getEntityRepository($fieldConfig->get('target_entity'));
     $data = $repo->createQueryBuilder('e')->select('e.id')->where('e.default = true')->getQuery()->getArrayResult();
     if ($data) {
         $data = array_shift($data);
     }
     $result = $data ? $data['id'] : null;
     $this->computedDefaultValues[$fieldName] = $result;
     return $result;
 }
 /**
  * @param AccountUserRole|AbstractRole $role
  * @param array                        $appendUsers
  * @param array                        $removeUsers
  */
 protected function fixUsersByAccount(AccountUserRole $role, array &$appendUsers, array &$removeUsers)
 {
     /** @var AccountUserRoleRepository $roleRepository */
     $roleRepository = $this->doctrineHelper->getEntityRepository($role);
     // Role moved to another account OR account added
     if ($role->getId() && ($this->originalAccount !== $role->getAccount() && $this->originalAccount !== null && $role->getAccount() !== null || $this->originalAccount === null && $role->getAccount() !== null)) {
         // Remove assigned users
         $assignedUsers = $roleRepository->getAssignedUsers($role);
         $removeUsers = array_replace($removeUsers, $assignedUsers);
         $appendNewUsers = array_diff($appendUsers, $removeUsers);
         $removeNewUsers = array_diff($removeUsers, $appendUsers);
         $removeUsers = $removeNewUsers;
         $appendUsers = $appendNewUsers;
     }
     if ($role->getAccount()) {
         // Security check
         $appendUsers = array_filter($appendUsers, function (AccountUser $user) use($role) {
             return $user->getAccount() === $role->getAccount();
         });
     }
 }
 /**
  * @return ActivityListRepository
  */
 public function getRepository()
 {
     return $this->doctrineHelper->getEntityRepository(ActivityList::ENTITY_NAME);
 }
 /**
  * @return AbstractWindowsStateRepository
  */
 protected function getRepository()
 {
     return $this->doctrineHelper->getEntityRepository($this->className);
 }
Exemple #25
0
 /**
  * @param $entity
  * @param $activityClass
  * @return mixed
  */
 protected function getActivitiesByEntity($entity, $activityClass)
 {
     $entityClass = ClassUtils::getRealClass($entity);
     $queryBuilder = $this->doctrineHelper->getEntityRepository(ActivityList::ENTITY_NAME)->getActivityListQueryBuilderByActivityClass($entityClass, $entity->getId(), $activityClass);
     return $queryBuilder->getQuery()->getResult();
 }
 /**
  * @param int $calendarId
  *
  * @return SystemCalendar|null
  */
 protected function findSystemCalendar($calendarId)
 {
     return $this->doctrineHelper->getEntityRepository('OroCalendarBundle:SystemCalendar')->find($calendarId);
 }
 /**
  * @return CategoryRepository
  */
 protected function getCategoryRepository()
 {
     return $this->doctrineHelper->getEntityRepository($this->categoryClass);
 }
 /**
  * @return AbstractEnumValue
  */
 protected function getDisabledStatus()
 {
     $className = ExtendHelper::buildEnumValueClassName('prod_status');
     return $this->doctrineHelper->getEntityRepository($className)->find(Product::STATUS_DISABLED);
 }
 /**
  * @return ProductPriceRepository
  */
 protected function getProductPriceRepository()
 {
     return $this->doctrineHelper->getEntityRepository($this->productPriceClass);
 }
 /**
  * @param int $identifier
  *
  * @return AbstractEnumValue
  */
 protected function getStatus($identifier)
 {
     $className = ExtendHelper::buildEnumValueClassName('mage_subscr_status');
     return $this->doctrineHelper->getEntityRepository($className)->find($identifier);
 }