/**
  * {@inheritdoc}
  */
 public function rewind()
 {
     if (!$this->iterableResult) {
         $this->iterableResult = $this->query->iterate(array(), Query::HYDRATE_ARRAY);
     }
     $this->iterableResult->rewind();
 }
 /**
  * {@inheritdoc}
  */
 public function getSlice($offset, $length)
 {
     $query = clone $this->query;
     $query->setParameters($this->query->getParameters());
     $query->setFirstResult($offset)->setMaxResults($length);
     return $query->getQuery()->getResult();
 }
Exemplo n.º 3
0
 /**
  * Constructor.
  *
  * Stores various parameters that are otherwise unavailable
  * because Doctrine\ORM\Query\SqlWalker keeps everything private without
  * accessors.
  *
  * @param \Doctrine\ORM\Query              $query
  * @param \Doctrine\ORM\Query\ParserResult $parserResult
  * @param array                            $queryComponents
  */
 public function __construct($query, $parserResult, array $queryComponents)
 {
     $this->platform = $query->getEntityManager()->getConnection()->getDatabasePlatform();
     $this->rsm = $parserResult->getResultSetMapping();
     $this->queryComponents = $queryComponents;
     parent::__construct($query, $parserResult, $queryComponents);
 }
Exemplo n.º 4
0
 /**
  * Adds a hint to a query object
  *
  * @param Query  $query
  * @param string $name
  * @param mixed  $value
  *
  * @return bool TRUE if the hint is added; otherwise, FALSE
  */
 public function addHint(Query $query, $name, $value)
 {
     $result = false;
     if ($name === Query::HINT_CUSTOM_TREE_WALKERS) {
         $walkers = $query->getHint(Query::HINT_CUSTOM_TREE_WALKERS);
         if (false === $walkers) {
             $walkers = [$value];
             $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, $walkers);
             $result = true;
         } elseif (!in_array($value, $walkers, true)) {
             $walkers[] = $value;
             $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, $walkers);
             $result = true;
         }
     } elseif ($name === Query::HINT_CUSTOM_OUTPUT_WALKER) {
         if ($query->getHint($name) !== $value) {
             $query->setHint($name, $value);
             $result = true;
         }
     } else {
         $query->setHint($name, $value);
         $result = true;
     }
     return $result;
 }
Exemplo n.º 5
0
 /**
  * Apply ACL filter
  *
  * @param  QueryBuilder | Query   $query
  * @param  array                  $permissions
  * @param  string | UserInterface $identity
  * @param  string                 $alias
  * @param  array|Query|QueryBuilder $extraCriteria
  *
  * @return Query
  */
 public function apply($query, array $permissions = array('VIEW'), $identity = null, $alias = null, $extraCriteria = false)
 {
     if (null === $identity) {
         $token = $this->securityContext->getToken();
         $identity = $token->getUser();
     }
     $query->setHint(static::HINT_ACL_EXTRA_CRITERIA, $this->getExtraCriteria($extraCriteria));
     if ($query instanceof QueryBuilder) {
         $query = $this->cloneQuery($query->getQuery());
     } elseif ($query instanceof Query) {
         $query = $this->cloneQuery($query);
     } else {
         throw new \Exception();
     }
     $maskBuilder = new MaskBuilder();
     foreach ($permissions as $permission) {
         $mask = constant(get_class($maskBuilder) . '::MASK_' . strtoupper($permission));
         $maskBuilder->add($mask);
     }
     $entity = $this->getEntityFromAlias($query, $alias);
     $metadata = $entity['metadata'];
     $alias = $entity['alias'];
     $table = $metadata->getQuotedTableName($this->em->getConnection()->getDatabasePlatform());
     $aclQuery = $this->getExtraQuery($this->getClasses($metadata), $this->getIdentifiers($identity), $maskBuilder->get());
     $hintAclMetadata = false !== $query->getHint('acl.metadata') ? $query->getHint('acl.metadata') : array();
     $hintAclMetadata[] = array('query' => $aclQuery, 'table' => $table, 'alias' => $alias);
     $query->setHint('acl.metadata', $hintAclMetadata);
     $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, $this->aclWalker);
     return $query;
 }
 /**
  * @param Query                              $query
  * @param array                              $paramMappings
  * @return array
  * @throws \Doctrine\ORM\Query\QueryException
  */
 protected function processParameterMappings(Query $query, $paramMappings)
 {
     $sqlParams = array();
     $types = array();
     /** @var Parameter $parameter */
     foreach ($query->getParameters() as $parameter) {
         $key = $parameter->getName();
         if (!isset($paramMappings[$key])) {
             throw QueryException::unknownParameter($key);
         }
         $value = $query->processParameterValue($parameter->getValue());
         $type = $parameter->getValue() === $value ? $parameter->getType() : Query\ParameterTypeInferer::inferType($value);
         foreach ($paramMappings[$key] as $position) {
             $types[$position] = $type;
         }
         $sqlPositions = $paramMappings[$key];
         $value = array($value);
         $countValue = count($value);
         for ($i = 0, $l = count($sqlPositions); $i < $l; $i++) {
             $sqlParams[$sqlPositions[$i]] = $value[$i % $countValue];
         }
     }
     if (count($sqlParams) != count($types)) {
         throw QueryException::parameterTypeMissmatch();
     }
     if ($sqlParams) {
         ksort($sqlParams);
         $sqlParams = array_values($sqlParams);
         ksort($types);
         $types = array_values($types);
     }
     return array($sqlParams, $types);
 }
Exemplo n.º 7
0
 /**
  * {@inheritDoc}
  *
  * @api
  */
 public function getItemCount()
 {
     try {
         return array_sum(array_map('current', $this->countQuery->getScalarResult()));
     } catch (NoResultException $e) {
         return 0;
     }
 }
 /**
  * @param Query $query
  */
 protected function applyTranslatorGedmoHints(Query &$query)
 {
     if (BELCEBUR_GEDMO_TRANSLATION_LOCALE !== 'BELCEBUR_GEDMO_TRANSLATION_LOCALE') {
         $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, $this->gedmoWalker);
         $query->setHint(TranslatableListener::HINT_TRANSLATABLE_LOCALE, BELCEBUR_GEDMO_TRANSLATION_LOCALE);
         $query->setHint(TranslatableListener::HINT_FALLBACK, TRUE);
     }
 }
Exemplo n.º 9
0
 public function __construct(DoctrineOrmPaginator $paginator)
 {
     $this->paginator = $paginator;
     $this->query = $paginator->getQuery();
     $this->firstResult = $this->query->getFirstResult();
     $this->maxResults = $this->query->getMaxResults();
     $this->totalItems = count($paginator);
 }
Exemplo n.º 10
0
 /**
  * @param Query $query
  *
  * @return array
  */
 protected function processMostSearchedQuery(Query $query)
 {
     $resultQuery = $query->getArrayResult();
     $result = [];
     foreach ($resultQuery as $answerArray) {
         $result[] = ['title' => $answerArray['title'], 'description' => $answerArray['description'], 'uri' => $this->routerInterface->generate('aalto_api_answer_show', ['slug' => $answerArray['slug']])];
     }
     return $result;
 }
 /**
  * @param Query $query
  * @param string $locale
  * @throws \Exception
  */
 protected function setTranslatableQueryHints(Query $query, $locale)
 {
     if (!class_exists('Gedmo\\Translatable\\TranslatableListener')) {
         throw new \Exception('"Translatable" extension missing. "stof/doctrine-extensions-bundle" needs to be installed');
     }
     $query->setHint(\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker');
     $query->setHint(\Gedmo\Translatable\TranslatableListener::HINT_TRANSLATABLE_LOCALE, $locale);
     $query->setHint(\Gedmo\Translatable\TranslatableListener::HINT_FALLBACK, 1);
 }
Exemplo n.º 12
0
 /**
  * Add a custom TreeWalker $walker class name to
  * be included in the CustomTreeWalker hint list
  * of the given $query
  *
  * @param Query $query
  * @param string $walker
  * @return void
  */
 public static function addCustomTreeWalker(Query $query, $walker)
 {
     $customTreeWalkers = $query->getHint(Query::HINT_CUSTOM_TREE_WALKERS);
     if ($customTreeWalkers !== false && is_array($customTreeWalkers)) {
         $customTreeWalkers = array_merge($customTreeWalkers, array($walker));
     } else {
         $customTreeWalkers = array($walker);
     }
     $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, $customTreeWalkers);
 }
Exemplo n.º 13
0
 /**
  * Clones a query
  * @param Query $query the query to be cloned
  * @return \Query the new query
  */
 private function cloneQuery($query)
 {
     /* @var $cloneQuery Query */
     $cloneQuery = clone $query;
     $cloneQuery->setParameters(clone $query->getParameters());
     foreach ($query->getHints() as $name => $value) {
         $cloneQuery->setHint($name, $value);
     }
     return $cloneQuery;
 }
Exemplo n.º 14
0
 /**
  * @param Query $query
  * @return Query
  */
 protected static function cloneQuery(Query $query)
 {
     /* @var $countQuery Query */
     $countQuery = clone $query;
     $params = $query->getParameters();
     foreach ($params as $key => $param) {
         $countQuery->setParameter($key, $param);
     }
     return $countQuery;
 }
Exemplo n.º 15
0
 /**
  * @param int $maxPerPage
  */
 public function setMaxPerPage($maxPerPage)
 {
     if ($maxPerPage > 0) {
         $this->maxPerPage = $maxPerPage;
         $this->query->setMaxResults($maxPerPage);
     } else {
         $this->maxPerPage = 0;
         $this->query->setMaxResults(Query::INFINITY);
     }
     $this->calculateFirstResult();
 }
Exemplo n.º 16
0
 private function getSingleResult(Query $query)
 {
     try {
         $result = $query->getSingleResult();
     } catch (NonUniqueResultException $e) {
         $result = null;
     } catch (NoResultException $e) {
         $result = null;
     }
     return $result;
 }
 /**
  * @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);
 }
Exemplo n.º 18
0
 public function close()
 {
     if ($this->clearEntitiesOnBatch) {
         $em = $this->query->getEntityManager();
         foreach ($this->clearEntitiesOnBatch as $e) {
             $em->clear($e);
         }
     }
     $this->query = null;
     $this->results = null;
 }
Exemplo n.º 19
0
 /**
  * @param \Kdyby\Persistence\Queryable $repository
  *
  * @throws UnexpectedValueException
  * @return \Doctrine\ORM\Query
  */
 protected function getQuery(Queryable $repository)
 {
     $query = $this->toQuery($this->doCreateQuery($repository));
     if ($this->lastQuery && $this->lastQuery->getDQL() === $query->getDQL()) {
         $query = $this->lastQuery;
     }
     if ($this->lastQuery !== $query) {
         $this->lastResult = new ResultSet($query, $this, $repository);
     }
     return $this->lastQuery = $query;
 }
 /**
  * Sets the total row count for this paginator
  *
  * Can be either an integer, or a Doctrine\ORM\Query object
  * which returns the count
  *
  * @param Query|integer $rowCount
  * @return void
  */
 public function setRowCount($rowCount)
 {
     if ($rowCount instanceof Query) {
         $this->rowCount = $rowCount->getSingleScalarResult();
     } else {
         if (is_integer($rowCount)) {
             $this->rowCount = $rowCount;
         } else {
             throw new \InvalidArgumentException("Invalid row count");
         }
     }
 }
Exemplo n.º 21
0
 public function paginate($page, Query $query, $itemsPerPage = 10)
 {
     if (!is_numeric($page)) {
         throw new \Exception('Valor no numerico para la paginacion');
     }
     $this->currentPage = (int) $page;
     $this->itemsPerPage = $itemsPerPage;
     $this->calLastPage(count($query->getResult()));
     $this->calRange();
     $query->setFirstResult($this->offset())->setMaxResults($this->itemsPerPage);
     return $query->getResult();
 }
 /**
  * @dataProvider functionsDataProvider
  * @param array $functions
  * @param string $dql
  * @param string $sql
  * @param string $expectedResult
  */
 public function testDqlFunction(array $functions, $dql, $sql, $expectedResult)
 {
     $configuration = $this->entityManager->getConfiguration();
     foreach ($functions as $function) {
         $this->registerDqlFunction($function['type'], $function['name'], $function['className'], $configuration);
     }
     $query = new Query($this->entityManager);
     $query->setDQL($dql);
     $this->assertEquals($sql, $query->getSQL(), sprintf('Unexpected SQL for "%s"', $dql));
     $result = $query->getArrayResult();
     $this->assertNotEmpty($result);
     $this->assertEquals($expectedResult, array_values(array_shift($result)), sprintf('Unexpected result for "%s"', $dql));
 }
 /**
  * Constructor.
  *
  * Stores various parameters that are otherwise unavailable
  * because Doctrine\ORM\Query\SqlWalker keeps everything private without
  * accessors.
  *
  * @param \Doctrine\ORM\Query              $query
  * @param \Doctrine\ORM\Query\ParserResult $parserResult
  * @param array                            $queryComponents
  */
 public function __construct($query, $parserResult, array $queryComponents)
 {
     $this->platform = $query->getEntityManager()->getConnection()->getDatabasePlatform();
     $this->rsm = $parserResult->getResultSetMapping();
     $this->queryComponents = $queryComponents;
     // Reset limit and offset
     $this->firstResult = $query->getFirstResult();
     $this->maxResults = $query->getMaxResults();
     $query->setFirstResult(null)->setMaxResults(null);
     $this->em = $query->getEntityManager();
     $this->quoteStrategy = $this->em->getConfiguration()->getQuoteStrategy();
     parent::__construct($query, $parserResult, $queryComponents);
 }
 /**
  * @param string $dql
  * @param string $expectedCountQuery
  * @param array  $sqlParameters
  * @param array  $types
  * @param array  $queryParameters
  *
  * @dataProvider getCountDataProvider
  */
 public function testCalculateCount($dql, $expectedCountQuery, array $sqlParameters = [], array $types = [], array $queryParameters = [])
 {
     /** @var $entityManager EntityManager|\PHPUnit_Framework_MockObject_MockObject */
     /** @var $connection Connection|\PHPUnit_Framework_MockObject_MockObject */
     /** @var $statement Statement|\PHPUnit_Framework_MockObject_MockObject */
     list($entityManager, $connection, $statement) = $this->prepareMocks();
     $query = new Query($entityManager);
     $query->setDQL($dql);
     $query->setParameters($queryParameters);
     $connection->expects($this->once())->method('executeQuery')->with($expectedCountQuery, $sqlParameters, $types)->will($this->returnValue($statement));
     $statement->expects($this->any())->method('fetch')->will($this->onConsecutiveCalls(['sclr_0' => self::TEST_COUNT], false));
     $statement->expects($this->any())->method('fetchColumn')->will($this->returnValue(self::TEST_COUNT));
     $this->assertEquals(self::TEST_COUNT, QueryCountCalculator::calculateCount($query));
 }
 /**
  * @param string $dql
  * @param array $sqlParameters
  * @param array $types
  * @param array $queryParameters
  *
  * @dataProvider getCountDataProvider
  */
 public function testCalculateCount($dql, array $sqlParameters, array $types, array $queryParameters = array())
 {
     /** @var $entityManager EntityManager|\PHPUnit_Framework_MockObject_MockObject */
     /** @var $connection Connection|\PHPUnit_Framework_MockObject_MockObject */
     /** @var $statement Statement|\PHPUnit_Framework_MockObject_MockObject */
     list($entityManager, $connection, $statement) = $this->prepareMocks();
     $query = new Query($entityManager);
     $query->setDQL($dql);
     $query->setParameters($queryParameters);
     $expectedSql = 'SELECT COUNT(*) FROM (' . $query->getSQL() . ') AS e';
     $connection->expects($this->once())->method('executeQuery')->with($expectedSql, $sqlParameters, $types)->will($this->returnValue($statement));
     $statement->expects($this->once())->method('fetchColumn')->with()->will($this->returnValue(self::TEST_COUNT));
     $this->assertEquals(self::TEST_COUNT, QueryCountCalculator::calculateCount($query));
 }
 /**
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  *
  * Copy of Doctrine\ORM\Query::processParameterMappings
  *
  * @param Query $query
  * @return array
  * @throws QueryException
  */
 public function processParameterMappings(Query $query)
 {
     $parser = new Parser($query);
     $parseResult = $parser->parse();
     $paramMappings = $parseResult->getParameterMappings();
     $resultSetMapping = $parseResult->getResultSetMapping();
     $paramCount = count($query->getParameters());
     $mappingCount = count($paramMappings);
     if ($paramCount > $mappingCount) {
         throw QueryException::tooManyParameters($mappingCount, $paramCount);
     } elseif ($paramCount < $mappingCount) {
         throw QueryException::tooFewParameters($mappingCount, $paramCount);
     }
     $sqlParams = [];
     $types = [];
     foreach ($query->getParameters() as $parameter) {
         $key = $parameter->getName();
         $value = $parameter->getValue();
         $rsm = $resultSetMapping;
         if (!isset($paramMappings[$key])) {
             throw QueryException::unknownParameter($key);
         }
         if (isset($rsm->metadataParameterMapping[$key]) && $value instanceof ClassMetadata) {
             $value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]);
         }
         $value = $query->processParameterValue($value);
         $type = $parameter->getValue() === $value ? $parameter->getType() : Query\ParameterTypeInferer::inferType($value);
         foreach ($paramMappings[$key] as $position) {
             $types[$position] = $type;
         }
         $sqlPositions = $paramMappings[$key];
         // optimized multi value sql positions away for now,
         // they are not allowed in DQL anyways.
         $value = [$value];
         $countValue = count($value);
         for ($i = 0, $l = count($sqlPositions); $i < $l; $i++) {
             $sqlParams[$sqlPositions[$i]] = $value[$i % $countValue];
         }
     }
     if (count($sqlParams) !== count($types)) {
         throw QueryException::parameterTypeMismatch();
     }
     if ($sqlParams) {
         ksort($sqlParams);
         $sqlParams = array_values($sqlParams);
         ksort($types);
         $types = array_values($types);
     }
     return [$sqlParams, $types];
 }
Exemplo n.º 27
0
 /**
  * {@inheritdoc}
  */
 public function apply($fromAlias, $fromIdentifier, $resourcePrefix, array $requesterIdentifiers, $mask, array $orX = [])
 {
     $this->query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'AlexDpy\\Acl\\Database\\Filter\\DoctrineOrmAclWalker');
     $this->query->setHint('acl_permissions_table_name', $this->getAclSchema()->getPermissionsTableName());
     $this->query->setHint('acl_resource_prefix', $resourcePrefix);
     $this->query->setHint('acl_requester_identifiers', $requesterIdentifiers);
     $this->query->setHint('acl_mask', $mask);
     $this->query->setHint('acl_from_alias', $fromAlias);
     $this->query->setHint('acl_from_identifier', $fromIdentifier);
     $this->query->setHint('acl_or_x', $orX);
     return $this->query;
 }
Exemplo n.º 28
0
 /**
  * @param Query|QueryBuilder $query
  * @param int                $page
  * @param int                $limit
  * @param Closure            $callback
  *
  * @return array
  */
 public function getPaginatedResult($query, $page, $limit, $callback = null)
 {
     $query->setFirstResult(($page - 1) * $limit)->setMaxResults($limit);
     if ($query instanceof QueryBuilder) {
         $query = $query->getQuery();
     }
     $items = $query->getResult();
     if ($callback == null) {
         $callback = function ($item) {
             return ['id' => $item->getId(), 'text' => (string) $item];
         };
     }
     $data = array_map($callback, $items);
     $more = count($data) >= $limit;
     return ['items' => $data, 'itemsPerPage' => $limit, 'more' => $more];
 }
Exemplo n.º 29
0
 /**
  * {@inheritdoc}
  */
 public function getIterator()
 {
     $offset = $this->query->getFirstResult();
     $length = $this->query->getMaxResults();
     if ($this->fetchJoinCollection) {
         $subQuery = $this->cloneQuery($this->query);
         if ($this->useOutputWalker($subQuery)) {
             $subQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\\ORM\\Tools\\Pagination\\LimitSubqueryOutputWalker');
         } else {
             $this->appendTreeWalker($subQuery, 'Doctrine\\ORM\\Tools\\Pagination\\LimitSubqueryWalker');
         }
         $subQuery->setFirstResult($offset)->setMaxResults($length);
         $ids = array_map('current', $subQuery->getScalarResult());
         $whereInQuery = $this->cloneQuery($this->query);
         // don't do this for an empty id array
         if (count($ids) == 0) {
             return new \ArrayIterator(array());
         }
         $this->appendTreeWalker($whereInQuery, 'Doctrine\\ORM\\Tools\\Pagination\\WhereInWalker');
         $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, count($ids));
         $whereInQuery->setFirstResult(null)->setMaxResults(null);
         $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, $ids);
         $whereInQuery->setCacheable($this->query->isCacheable());
         $result = $whereInQuery->getResult($this->query->getHydrationMode());
     } else {
         $result = $this->cloneQuery($this->query)->setMaxResults($length)->setFirstResult($offset)->setCacheable($this->query->isCacheable())->getResult($this->query->getHydrationMode());
     }
     return new \ArrayIterator($result);
 }
 /**
  * {@inheritdoc}
  */
 public function rewind()
 {
     if ($this->iterator) {
         throw new InvalidMethodCallException('Cannot rewind a Doctrine\\ORM\\Query');
     }
     $this->iterator = $this->query->iterate();
     $this->iterator->rewind();
 }