/** * @param Repository $EntityRepository * @param array $Filter array( 'ColumnName' => 'Value', ... ) */ function __construct(Repository $EntityRepository, $Filter = array()) { $this->QueryBuilder = $EntityRepository->createQueryBuilder(self::QUERY_BUILDER_ALIAS); $this->ColumnNames = $this->QueryBuilder->getEntityManager()->getClassMetadata($EntityRepository->getClassName())->getFieldNames(); $this->Request = $this->getRequest()->getParameterArray(); $this->setFilter($Filter); $this->setSearch(); $this->setOrderBy(); }
/** * Add completeness joins to query builder * * @param string $completenessAlias the join alias * @param string $locale the locale * @param sting $scope the scope * * @return CompletenessJoin */ public function addJoins($completenessAlias, $locale, $scope) { $rootAlias = $this->qb->getRootAlias(); $localeAlias = $completenessAlias . 'Locale'; $channelAlias = $completenessAlias . 'Channel'; $rootEntity = current($this->qb->getRootEntities()); $completenessMapping = $this->qb->getEntityManager()->getClassMetadata($rootEntity)->getAssociationMapping('completenesses'); $completenessClass = $completenessMapping['targetEntity']; $this->qb->leftJoin('PimCatalogBundle:Locale', $localeAlias, 'WITH', $localeAlias . '.code = :cLocaleCode')->leftJoin('PimCatalogBundle:Channel', $channelAlias, 'WITH', $channelAlias . '.code = :cScopeCode')->leftJoin($completenessClass, $completenessAlias, 'WITH', $completenessAlias . '.locale = ' . $localeAlias . '.id AND ' . $completenessAlias . '.channel = ' . $channelAlias . '.id AND ' . $completenessAlias . '.product = ' . $rootAlias . '.id')->setParameter('cLocaleCode', $locale)->setParameter('cScopeCode', $scope); return $this; }
/** * This method alters the query to return a clean set of object with a working * set of Object * * @param \Doctrine\ORM\QueryBuilder $queryBuilder * @return void */ private function getFixedQueryBuilder(QueryBuilder $queryBuilder) { $queryBuilderId = clone $queryBuilder; // step 1 : retrieve the targeted class $from = $queryBuilderId->getDQLPart('from'); $class = $from[0]->getFrom(); // step 2 : retrieve the column id $idName = current($queryBuilderId->getEntityManager()->getMetadataFactory()->getMetadataFor($class)->getIdentifierFieldNames()); // step 3 : retrieve the different subjects id $select = sprintf('%s.%s', $queryBuilderId->getRootAlias(), $idName); $queryBuilderId->resetDQLPart('select'); $queryBuilderId->add('select', 'DISTINCT ' . $select); $results = $queryBuilderId->getQuery()->execute(array(), Query::HYDRATE_ARRAY); $idx = array(); $connection = $queryBuilder->getEntityManager()->getConnection(); foreach ($results as $id) { $idx[] = $connection->quote($id[$idName]); } // step 4 : alter the query to match the targeted ids if (count($idx) > 0) { $queryBuilder->andWhere(sprintf('%s IN (%s)', $select, implode(',', $idx))); $queryBuilder->setMaxResults(null); $queryBuilder->setFirstResult(null); } return $queryBuilder; }
/** * Gets the full class name if the given join expression represents an entity name in form "bundle:class" * * @param string $joinExpr * * @return string */ protected function resolveEntityClass($joinExpr) { $parts = explode(':', $joinExpr); if (count($parts) !== 2) { return $joinExpr; } return $this->originalQueryBuilder->getEntityManager()->getConfiguration()->getEntityNamespace($parts[0]) . '\\' . $parts[1]; }
protected function resetBuilder() { $rootEntities = $this->qb->getRootEntities(); $this->qb = $this->qb->getEntityManager()->getRepository($rootEntities[0])->createQueryBuilder('x'); $this->joinAliases = []; $this->parametersMap = []; $this->orderBy = []; }
/** * Initialize the column id of the targeted class. * * @return string */ protected function initIdFieldName() { /** @var $from \Doctrine\ORM\Query\Expr\From */ $from = current($this->originalQb->getDQLPart('from')); $class = $from->getFrom(); $idNames = $this->originalQb->getEntityManager()->getMetadataFactory()->getMetadataFor($class)->getIdentifierFieldNames(); $this->idFieldName = current($idNames); }
private function createNumRowsSubQuery() { $parts = $this->query->getDQLParts(); $from = $parts['from'][0]; $where = $parts['where']; $entityManager = $this->query->getEntityManager(); $queryBuilder = $entityManager->createQueryBuilder(); $queryBuilder->select('COUNT(DISTINCT countAlias.id)')->from($from->getFrom(), 'countAlias'); $aliasCount = 1; $aliases = array($from->getAlias() => 'countAlias'); foreach ($parts['join'] as $joinSource => $joins) { if (!array_key_exists($joinSource, $aliases)) { $aliases[$joinSource] = 'countAlias' . $aliasCount; ++$aliasCount; } foreach ($joins as $join) { if (!array_key_exists($join->getAlias(), $aliases)) { $aliases[$join->getAlias()] = 'countAlias' . $aliasCount; ++$aliasCount; } preg_match('#[a-zA-Z_]*\\.+#', $join->getJoin(), $matches); $joinCondition = preg_replace('#[a-zA-Z_]*\\.+#', $aliases[substr($matches[0], 0, -1)] . '.', $join->getJoin()); switch ($join->getJoinType()) { case \Doctrine\ORM\Query\Expr\Join::INNER_JOIN: $queryBuilder->innerJoin($joinCondition, $aliases[$join->getAlias()]); break; case \Doctrine\ORM\Query\Expr\Join::LEFT_JOIN: $queryBuilder->leftJoin($joinCondition, $aliases[$join->getAlias()]); break; default: throw new \Exception('Unknow join type'); break; } } } if ($where) { $whereCondition = $where->__toString(); preg_match_all('#([a-zA-Z_]*)\\.+#', $whereCondition, $matches); foreach ($matches[1] as $alias) { $whereCondition = preg_replace('#' . $alias . '\\.+#', $aliases[$alias] . '.', $whereCondition); } $queryBuilder->where($whereCondition); } return $queryBuilder; }
/** * {@inheritdoc} */ public function applyToCollection(ResourceInterface $resource, QueryBuilder $queryBuilder) { $classMetaData = $queryBuilder->getEntityManager()->getClassMetadata($resource->getEntityClass()); $identifiers = $classMetaData->getIdentifier(); if (null !== $this->order && 1 === count($identifiers)) { $identifier = $identifiers[0]; $queryBuilder->addOrderBy('o.' . $identifier, $this->order); } }
/** * Add completeness joins to query builder * * @param string $completenessAlias the join alias * @param string $locale the locale * @param string $scope the scope * * @return CompletenessJoin */ public function addJoins($completenessAlias, $locale, $scope) { $rootAlias = $this->qb->getRootAliases()[0]; $localeAlias = $completenessAlias . 'Locale'; $channelAlias = $completenessAlias . 'Channel'; $rootEntity = $this->qb->getRootEntities()[0]; $completenessMapping = $this->qb->getEntityManager()->getClassMetadata($rootEntity)->getAssociationMapping('completenesses'); $completenessClass = $completenessMapping['targetEntity']; $joinCondition = sprintf('%s.product = %s.id', $completenessAlias, $rootAlias); $this->qb->leftJoin('PimCatalogBundle:Channel', $channelAlias, 'WITH', $channelAlias . '.code = :cScopeCode')->setParameter('cScopeCode', $scope); $joinCondition .= sprintf(' AND %s.channel = %s.id', $completenessAlias, $channelAlias); if (null !== $locale) { $this->qb->leftJoin('PimCatalogBundle:Locale', $localeAlias, 'WITH', sprintf('%s.code = :%scLocaleCode', $localeAlias, $localeAlias))->setParameter($localeAlias . 'cLocaleCode', $locale); $joinCondition .= sprintf(' AND %s.locale = %s.id', $completenessAlias, $localeAlias); } $this->qb->leftJoin($completenessClass, $completenessAlias, 'WITH', $joinCondition); return $this; }
/** * {@inheritdoc} */ public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null) { $classMetaData = $queryBuilder->getEntityManager()->getClassMetadata($resourceClass); $identifiers = $classMetaData->getIdentifier(); if (null !== $this->order) { foreach ($identifiers as $identifier) { $queryBuilder->addOrderBy('o.' . $identifier, $this->order); } } }
protected function initializeDataStructure($tableName, $primaryKey) { $dataStructure = new Structures\DataStructure($tableName, $primaryKey); $this->setDataStructure($dataStructure); $entityManager = $this->queryBuilder->getEntityManager(); $classMetadata = $entityManager->getClassMetadata($tableName); Helpers::setStructureFromColumns($dataStructure, $this->determineFromColumns($classMetadata)); foreach ($classMetadata->getAssociationNames() as $associationName) { $targetClass = $classMetadata->getAssociationTargetClass($associationName); $targetMetadata = $entityManager->getClassMetadata($targetClass); $associations = $classMetadata->getAssociationsByTargetClass($targetClass); $primaryColumns = $targetMetadata->getIdentifierColumnNames(); foreach ($associations as $association) { $dataStructure->getOrCreateTableStructure($targetClass, reset($primaryColumns)); $associationsType = $association['type']; if ($associationsType === $classMetadata::ONE_TO_ONE) { if ($association['sourceEntity'] === $tableName) { $referencedColumn = reset($association['targetToSourceKeyColumns']); } if (!isset($referencedColumn)) { throw new InvalidStateException(sprintf('Can not find referenced column name for field %s.', $associationName)); } $dataStructure->addOneToOne($associationName, $targetClass, $referencedColumn); } elseif ($associationsType === $classMetadata::MANY_TO_ONE) { if ($association['sourceEntity'] === $tableName) { $referencedColumn = reset($association['targetToSourceKeyColumns']); } if (!isset($referencedColumn)) { throw new InvalidStateException(sprintf('Can not find referenced column name for field %s.', $associationName)); } $dataStructure->addManyToOne($associationName, $targetClass, $referencedColumn); } elseif ($associationsType === $classMetadata::ONE_TO_MANY) { foreach ($targetMetadata->getAssociationMappings() as $joinedAssociation) { if ($joinedAssociation['inversedBy'] === $associationName) { $referencedColumn = reset($joinedAssociation['targetToSourceKeyColumns']); } } if (!isset($referencedColumn)) { throw new InvalidStateException(sprintf('Can not find referenced column name for field %s. Is `inversedBy` set in property annotation?', $associationName)); } $dataStructure->addOneToMany($associationName, $targetClass, $referencedColumn); } elseif ($associationsType === $classMetadata::MANY_TO_MANY) { if (!isset($association['joinTable'])) { throw new InvalidStateException(sprintf('Can not find joinColumn settings for field %s. Is `joinColumn` set in property annotation?', $associationName)); } $joinTable = $association['joinTable']; if (isset($joinTable['joinColumns']) && $joinTable['joinColumns']) { $joinColumn = reset($joinTable['joinColumns']); $inverseJoinColumn = reset($joinTable['inverseJoinColumns']); $dataStructure->addManyToMany($associationName, $targetClass, $inverseJoinColumn['name'], $joinTable['name'], $joinColumn['name']); } } } } }
/** * @inheritdoc */ public function normalize(Query $query, QueryBuilder $queryBuilder, $hydratorClass = null) { /* * Add custom hydrator */ $emConfig = $queryBuilder->getEntityManager()->getConfiguration(); $hydrator = new \ReflectionClass($hydratorClass); $hydratorName = $hydrator->getShortName(); $emConfig->addCustomHydrationMode($hydratorName, $hydratorClass); return $query->getResult($hydratorName); }
/** * Ensure that filtering applied and query builder wrapped in buffered iterator * if data source is query builder or just an entity name * * @param ContextInterface $context */ protected function ensureInitialized(ContextInterface $context) { if (null !== $this->qb) { if ($context->hasOption(self::ID_FILTER)) { $optionValue = $context->getOption(self::ID_FILTER); $em = $this->qb->getEntityManager(); $entityNames = $this->qb->getRootEntities(); $classMetadata = $em->getClassMetadata(reset($entityNames)); $identifier = $classMetadata->getSingleIdentifierFieldName(); if (is_array($optionValue)) { $this->qb->andWhere($this->qb->expr()->in('o.' . $identifier, ':id')); $this->qb->setParameter('id', $optionValue); } else { $this->qb->andWhere('o.' . $identifier . ' = :id'); } $this->qb->setParameter('id', $optionValue); } $this->setSourceIterator(new BufferedQueryResultIterator($this->qb)); } }
/** * Left joins relations to eager load. * * @param ResourceInterface $resource * @param QueryBuilder $queryBuilder */ private function joinRelations(ResourceInterface $resource, QueryBuilder $queryBuilder) { $classMetaData = $queryBuilder->getEntityManager()->getClassMetadata($resource->getEntityClass()); foreach ($classMetaData->getAssociationNames() as $i => $association) { $mapping = $classMetaData->associationMappings[$association]; if (ClassMetadataInfo::FETCH_EAGER === $mapping['fetch']) { $queryBuilder->leftJoin('o.' . $association, 'a' . $i); $queryBuilder->addSelect('a' . $i); } } }
/** * Apply ACL restriction to query builder. * * @param QueryBuilder $queryBuilder * @param string $tableAlias */ public function applyAcl(QueryBuilder $queryBuilder, $tableAlias) { $taggableEntities = $this->getTaggableEntities($queryBuilder->getEntityManager()); $allowedEntities = $this->getAllowedEntities($taggableEntities); if (count($allowedEntities) != count($taggableEntities)) { if ($allowedEntities) { $queryBuilder->andWhere($tableAlias . '.entityName IN(:allowedEntities)')->setParameter('allowedEntities', $allowedEntities); } else { // Do not show any result if all entities are prohibited $queryBuilder->andWhere('1 = 0'); } } }
/** * Defines default identifiers from query builder in order to optimize count queries. * * @return $this * * @throws \Doctrine\Common\Persistence\Mapping\MappingException */ public function setDefaultIdentifierFieldNames() { //Default identifier for table rows $rootEntity = $this->queryBuilder->getRootEntities()[0]; $metadata = $this->queryBuilder->getEntityManager()->getMetadataFactory()->getMetadataFor($rootEntity); $identifiers = array(); foreach ($metadata->getIdentifierFieldNames() as $identifierFieldName) { $identifiers[] = $this->getAlias() . '.' . $identifierFieldName; } $rootEntityIdentifier = implode(',', $identifiers); $this->setIdentifierFieldNames($rootEntityIdentifier ?: null); return $this; }
/** * @{inheritDoc} */ public function getIterator() { if ($this->queryBuilder) { return new CollectionMapIterator($this->queryBuilder->getQuery()->iterate(), function ($row) { $entity = $row[0]; if ($this->detaching) { $this->queryBuilder->getEntityManager()->detach($entity); } return $entity; }); } else { return parent::getIterator(); } }
/** * This method alters the query to return a clean set of object with a working * set of Object * * @param QueryBuilder $queryBuilder * * @return QueryBuilder */ private function getFixedQueryBuilder(QueryBuilder $queryBuilder) { $queryBuilderId = clone $queryBuilder; // step 1 : retrieve the targeted class $from = $queryBuilderId->getDQLPart('from'); $class = $from[0]->getFrom(); // step 2 : retrieve the column id $idName = current($queryBuilderId->getEntityManager()->getMetadataFactory()->getMetadataFor($class)->getIdentifierFieldNames()); // step 3 : retrieve the different subjects id $rootAliases = $queryBuilderId->getRootAliases(); $rootAlias = $rootAliases[0]; $select = sprintf('%s.%s', $rootAlias, $idName); $queryBuilderId->resetDQLPart('select'); $queryBuilderId->add('select', 'DISTINCT ' . $select); // for SELECT DISTINCT, ORDER BY expressions must appear in select list /* Consider SELECT DISTINCT x FROM tab ORDER BY y; For any particular x-value in the table there might be many different y values. Which one will you use to sort that x-value in the output? */ // todo : check how doctrine behave, potential SQL injection here ... if ($this->getSortBy()) { $sortBy = $this->getSortBy(); if (strpos($sortBy, '.') === false) { // add the current alias $sortBy = $rootAlias . '.' . $sortBy; } $sortBy .= ' AS __order_by'; $queryBuilderId->addSelect($sortBy); } $results = $queryBuilderId->getQuery()->execute(array(), Query::HYDRATE_ARRAY); $idx = array(); $connection = $queryBuilder->getEntityManager()->getConnection(); foreach ($results as $id) { $idx[] = $connection->quote($id[$idName]); } // step 4 : alter the query to match the targeted ids if (count($idx) > 0) { $queryBuilder->andWhere(sprintf('%s IN (%s)', $select, implode(',', $idx))); $queryBuilder->setMaxResults(null); $queryBuilder->setFirstResult(null); } return $queryBuilder; }
/** * @param QueryBuilder $queryBuilder * @param string|null $currency */ public function applyPriceListLimitations(QueryBuilder $queryBuilder, $currency = null) { $token = $this->tokenStorage->getToken(); /** @var AccountUser $user */ if ($token && ($user = $token->getUser()) instanceof AccountUser) { $priceList = $this->priceListTreeHandler->getPriceList($user); if ($priceList) { $rootAliases = $queryBuilder->getRootAliases(); $rootAlias = $rootAliases[0]; // Select only products that are in specific price list $limitationQb = $queryBuilder->getEntityManager()->createQueryBuilder(); $limitationQb->from('OroB2BPricingBundle:ProductPrice', '_productPrice')->select('IDENTITY(_productPrice.product)')->where($limitationQb->expr()->eq('_productPrice.priceList', ':_priceList'))->andWhere($limitationQb->expr()->eq('_productPrice.product', $rootAlias)); if ($currency) { $limitationQb->andWhere($queryBuilder->expr()->eq('_productPrice.currency', ':currency')); $queryBuilder->setParameter('currency', strtoupper($currency)); } $queryBuilder->andWhere($queryBuilder->expr()->exists($limitationQb))->setParameter('_priceList', $priceList); } } }
function it_adds_a_filter_on_a_field_in_the_query(QueryBuilder $qb, Expr $expr, EntityManager $em, ClassMetadata $cm, Expr\Comparison $comparison) { $qb->expr()->willReturn($expr); $qb->getRootAlias()->willReturn('p'); $qb->getRootEntities()->willReturn([]); $qb->getEntityManager()->willReturn($em); $em->getClassMetadata(false)->willReturn($cm); $comparison->__toString()->willReturn('filterCompleteness.ratio < 100'); $cm->getAssociationMapping('completenesses')->willReturn(['targetEntity' => 'test']); $expr->literal('100')->willReturn('100'); $expr->lt(Argument::any(), '100')->willReturn($comparison); $this->setQueryBuilder($qb); $qb->leftJoin('PimCatalogBundle:Locale', Argument::any(), 'WITH', Argument::any())->willReturn($qb); $qb->leftJoin('PimCatalogBundle:Channel', Argument::any(), 'WITH', Argument::any())->willReturn($qb); $qb->leftJoin('test', Argument::any(), 'WITH', Argument::any())->willReturn($qb); $qb->setParameter('cLocaleCode', Argument::any())->willReturn($qb); $qb->setParameter('cScopeCode', Argument::any())->willReturn($qb); $qb->andWhere('filterCompleteness.ratio < 100')->shouldBeCalled(); $this->addFieldFilter('completeness', '<', 100, 'en_US', 'mobile'); }
public function filter(QueryBuilder $queryBuilder, $metadata, $option) { if (isset($option['where'])) { if ($option['where'] === 'and') { $queryType = 'andWhere'; } elseif ($option['where'] === 'or') { $queryType = 'orWhere'; } } if (!isset($queryType)) { $queryType = 'andWhere'; } $orX = $queryBuilder->expr()->orX(); $em = $queryBuilder->getEntityManager(); $qb = $em->createQueryBuilder(); foreach ($option['conditions'] as $condition) { $filter = $this->getFilterManager()->get(strtolower($condition['type']), array($this->getFilterManager())); $filter->filter($qb, $metadata, $condition); } $dqlParts = $qb->getDqlParts(); $orX->addMultiple($dqlParts['where']->getParts()); $queryBuilder->setParameters(new ArrayCollection(array_merge_recursive($queryBuilder->getParameters()->toArray(), $qb->getParameters()->toArray()))); $queryBuilder->{$queryType}($orX); }
/** * Adds filter by $entity DQL to the given query builder * * @param QueryBuilder $qb The query builder that is used to get the list of activities * @param string $entityClass The target entity class * @param mixed $entityId The target entity id * @param string|null $activityEntityClass This parameter should be specified * if the query has more than one root entity * * @throws \RuntimeException */ public function addFilterByTargetEntity(QueryBuilder $qb, $entityClass, $entityId, $activityEntityClass = null) { $activityEntityAlias = null; $rootEntities = $qb->getRootEntities(); if (empty($rootEntities)) { throw new \RuntimeException('The query must have at least one root entity.'); } if (empty($activityEntityClass)) { if (count($rootEntities) > 1) { throw new \RuntimeException('The $activityEntityClass must be specified if the query has several root entities.'); } $activityEntityClass = $rootEntities[0]; $activityEntityAlias = $qb->getRootAliases()[0]; } else { $normalizedActivityEntityClass = ClassUtils::getRealClass($this->entityClassResolver->getEntityClass($activityEntityClass)); foreach ($rootEntities as $i => $className) { $className = $this->entityClassResolver->getEntityClass($className); if ($className === $normalizedActivityEntityClass) { $activityEntityAlias = $qb->getRootAliases()[$i]; break; } } if (empty($activityEntityAlias)) { throw new \RuntimeException(sprintf('The "%s" must be the root entity.', $activityEntityClass)); } } $activityIdentifierFieldName = $this->doctrineHelper->getSingleEntityIdentifierFieldName($activityEntityClass); $targetIdentifierFieldName = $this->doctrineHelper->getSingleEntityIdentifierFieldName($entityClass); $filterQuery = $qb->getEntityManager()->createQueryBuilder()->select(sprintf('filterActivityEntity.%s', $activityIdentifierFieldName))->from($activityEntityClass, 'filterActivityEntity')->innerJoin(sprintf('filterActivityEntity.%s', ExtendHelper::buildAssociationName($entityClass, ActivityScope::ASSOCIATION_KIND)), 'filterTargetEntity')->where(sprintf('filterTargetEntity.%s = :targetEntityId', $targetIdentifierFieldName))->getQuery(); $qb->andWhere($qb->expr()->in(sprintf('%s.%s', $activityEntityAlias, $activityIdentifierFieldName), $filterQuery->getDQL()))->setParameter('targetEntityId', $entityId); }
private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions) { $select = []; $entityManager = $queryBuilder->getEntityManager(); $targetClassMetadata = $entityManager->getClassMetadata($entity); foreach ($this->propertyNameCollectionFactory->create($entity) as $property) { $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions); if (true === $propertyMetadata->isIdentifier()) { $select[] = $property; continue; } //the field test allows to add methods to a Resource which do not reflect real database fields if (true === $targetClassMetadata->hasField($property) && true === $propertyMetadata->isReadable()) { $select[] = $property; } } $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select))); }
/** * @param \Doctrine\ORM\QueryBuilder $qb */ public function setExportQueryBuilder(\Doctrine\ORM\QueryBuilder $qb) { $this->qb = $qb; $this->setEntityManager($qb->getEntityManager()); }
/** * @param int $index * @return ClassMetadata */ protected function getClassMetadata($index = 0) { $rootClasses = $this->qb->getRootEntities(); return $this->qb->getEntityManager()->getClassMetadata($rootClasses[$index]); }
protected function getClassMetadata() { $class = $this->qb->getDQLPart('from')[0]->getFrom(); return $this->qb->getEntityManager()->getClassMetadata($class); }
/** * Get root entities config data * * @param QueryBuilder $query * @return array with root entities config */ protected function getRootIds(QueryBuilder $query) { $groupParts = $this->getGroupParts(); $rootIds = []; if (empty($groupParts)) { $rootIdentifiers = $query->getEntityManager()->getClassMetadata($query->getRootEntities()[0])->getIdentifier(); $rootAlias = $query->getRootAliases()[0]; foreach ($rootIdentifiers as $field) { $rootIds[] = ['fieldAlias' => $field, 'alias' => $field, 'entityAlias' => $rootAlias]; } } else { foreach ($groupParts as $groupPart) { if (strpos($groupPart, '.')) { list($rootAlias, $rootIdentifierPart) = explode('.', $groupPart); $rootIds[] = ['fieldAlias' => $rootIdentifierPart, 'entityAlias' => $rootAlias, 'alias' => $rootIdentifierPart]; } else { $selectParts = $this->masterQB->getDQLPart('select'); /** @var Select $selectPart */ foreach ($selectParts as $selectPart) { foreach ($selectPart->getParts() as $part) { if (preg_match('/^(.*)\\sas\\s(.*)$/i', $part, $matches)) { if (count($matches) == 3 && $groupPart == $matches[2]) { $rootIds[] = ['fieldAlias' => $matches[1], 'alias' => $matches[2]]; } } else { $rootIds[] = ['fieldAlias' => $groupPart, 'alias' => $groupPart]; } } } } } } return $rootIds; }
/** * @param QueryBuilder $queryBuilder * @param Segment $segment * * @return string */ protected function getIdentityFieldWithAlias(QueryBuilder $queryBuilder, Segment $segment) { $tableAliases = $queryBuilder->getRootAliases(); $em = $queryBuilder->getEntityManager(); $entityMetadata = $em->getClassMetadata($segment->getEntity()); $idField = $entityMetadata->getSingleIdentifierFieldName(); if ($this->isDynamic($segment)) { return $tableAliases[0] . '.' . $idField; } $idFieldType = $entityMetadata->getTypeOfField($idField); $fieldToSelect = SegmentSnapshot::ENTITY_REF_FIELD; if ($idFieldType == 'integer') { $fieldToSelect = SegmentSnapshot::ENTITY_REF_INTEGER_FIELD; } return $tableAliases[0] . '.' . $fieldToSelect; }
/** * Creates new instance of QueryBuilder object * * @return QueryBuilder */ public function createQueryBuilder() { return $this->qb->getEntityManager()->createQueryBuilder(); }
/** * Gets entity name. * * @return EntityManager EntityManager */ public function getEntityManager() { return $this->queryBuilder->getEntityManager(); }