Example #1
1
 public function paginateQuery(Query $query, Search $search)
 {
     $results = $query->getResult();
     $limit = $search->getListAll() ? count($results) ? count($results) : 1 : $search->getMaxPerPage();
     $adapter = new DoctrineORMAdapter($query);
     $paginator = new Pagerfanta($adapter);
     $paginator->setMaxPerPage($limit);
     $paginator->setCurrentPage($search->getPage());
     $paginator->getCurrentPageResults();
     // Just to cache the consult
     $paginator->getNbResults();
     // Just to cache the results
     return $paginator;
 }
 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();
 }
Example #3
0
 /**
  * Loads the collection into memory.
  *
  * @return void
  */
 private function load()
 {
     if (!$this->isLoaded) {
         $this->elements = $this->query->getResult();
         $this->isLoaded = true;
     }
 }
Example #4
0
 /**
  * Executes query and saving query SQL to list (if needed)
  *
  * @access   public
  * @param    boolean $noResults returns no results, if TRUE
  * @return   array
  * @since    1.0.0-alpha
  * @version  1.0.0-alpha
  */
 public function execute($noResults = FALSE)
 {
     if (!$noResults) {
         static::$mResult = $this->oQuery->getResult();
     } else {
         static::$mResult = $this->oQuery->execute();
     }
     return static::$mResult;
 }
 /**
  * @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);
 }
Example #6
0
 /**
  * {@inheritdoc}
  */
 public function paginate(Query $query, $results, $offset, $arrayResult = true)
 {
     if ($results <= 0 || $results > $this->maxResults) {
         $results = $this->defaultResults;
     }
     if ($offset < 0) {
         $offset = 0;
     }
     $paginator = new Paginator($query, false);
     $query->setFirstResult($offset)->setMaxResults($results);
     if ($arrayResult) {
         $result = $query->getArrayResult();
     } else {
         $result = $query->getResult();
     }
     return ['recordsTotal' => count($paginator), 'recordsFiltered' => count($paginator), 'data' => $result];
 }
Example #7
0
 /**
  * @param int|null
  * @return \ArrayIterator
  */
 public function getIterator($hydrationMode = NULL)
 {
     if ($this->iterator !== NULL) {
         return $this->iterator;
     }
     if ($hydrationMode !== NULL) {
         $this->query->setHydrationMode($hydrationMode);
     }
     $this->frozen = TRUE;
     if ($this->fetchJoinCollection && ($this->query->getMaxResults() > 0 || $this->query->getFirstResult() > 0)) {
         $this->iterator = $this->createPaginatedQuery($this->query)->getIterator();
     } else {
         $this->iterator = new \ArrayIterator($this->query->getResult(NULL));
     }
     if ($this->repository && $this->queryObject) {
         $this->queryObject->queryFetched($this->repository, $this->iterator);
     }
     return $this->iterator;
 }
Example #8
0
 /**
  * @param int $hydrationMode
  * @throws QueryException
  * @return \ArrayIterator
  */
 public function getIterator($hydrationMode = ORM\AbstractQuery::HYDRATE_OBJECT)
 {
     if ($this->iterator !== NULL) {
         return $this->iterator;
     }
     $this->query->setHydrationMode($hydrationMode);
     try {
         $this->frozen = TRUE;
         if ($this->fetchJoinCollection && ($this->query->getMaxResults() > 0 || $this->query->getFirstResult() > 0)) {
             $this->iterator = $this->createPaginatedQuery($this->query)->getIterator();
         } else {
             $this->iterator = new \ArrayIterator($this->query->getResult(NULL));
         }
         if ($this->queryObject !== NULL && $this->repository !== NULL) {
             $this->queryObject->postFetch($this->repository, $this->iterator);
         }
         return $this->iterator;
     } catch (ORMException $e) {
         throw new QueryException($e, $this->query, $e->getMessage());
     }
 }
 /**
  * Get result identities
  *
  * @param \Doctrine\ORM\Query $dqlQuery
  * @return array
  * @throws \Zend_Auth_Adapter_Exception
  */
 protected function _authenticateQueryDql(\Doctrine\ORM\Query $dqlQuery)
 {
     try {
         $resultIdentities = $dqlQuery->getResult();
     } catch (\Exception $e) {
         throw new \Zend_Auth_Adapter_Exception('The supplied parameters to Extlib\\Auth\\Adapter\\Doctrine2 failed to ' . 'produce a valid sql statement, please check table and column names ' . 'for validity.', 0, $e);
     }
     return $resultIdentities;
 }
Example #10
0
 /**
  * Performs a given database selection and post-processed the results.
  *
  * @param Doctrine\ORM\Query $query       The Query instance to be executed.
  * @param string             $orderBy     The order-by clause to use when retrieving the collection (optional) (default='').
  * @param boolean            $isPaginated Whether the given query uses a paginator or not (optional) (default=false).
  *
  * @return Array with retrieved collection.
  */
 public function retrieveCollectionResult(Query $query, $orderBy = '', $isPaginated = false)
 {
     $result = $query->getResult();
     if ($orderBy == 'RAND()') {
         // each entry in $result looks like array(0 => actualRecord, 'randomIdentifiers' => randomId)
         $resRaw = array();
         foreach ($result as $resultRow) {
             $resRaw[] = $resultRow[0];
         }
         $result = $resRaw;
     }
     return $result;
 }
Example #11
0
 /**
  *
  * @param Query $query        	
  * @param string $cacheItemKey        	
  * @return array|bool|mixed|string
  */
 protected function getCachedResult(Query $query, $cacheItemKey = '', $ttl = 0)
 {
     if (!$cacheItemKey) {
         $cacheItemKey = ($this->cache_prefix ? $this->cache_prefix : get_called_class()) . md5($query->getDQL());
     }
     $cache = $this->getEntityManager()->getConfiguration()->getResultCacheImpl();
     // test if item exists in the cache
     if ($cache->contains($cacheItemKey)) {
         // retrieve item from cache
         $items = $cache->fetch($cacheItemKey);
     } else {
         // retrieve item from repository
         $items = $query->getResult();
         // save item to cache
         $cache->save($cacheItemKey, $items, $ttl);
     }
     return $items;
 }
Example #12
0
 private function loadQuery()
 {
     if ($this->result === null) {
         $this->result = $this->query->getResult();
     }
 }
Example #13
0
        /**
     * @route: blog_new
     * Tag Controller
     */
    public function newAction()
    {
        // entity manager and query builder objects
        $em = $this->getEm();


        $query = new Query($em);
        $query->setDQL(
            'SELECT p,comments
                FROM Bundle\BlogBundle\Entity\Post p
                JOIN p.comments comments
                ORDER BY p.date DESC'
        );
        $query->setMaxResults(1);
        //$query->setParameter(1, $slug);
        $posts = $query->getResult();


        return $this->render('BlogBundle:Blog:post.html.twig', array(
            'post' => $posts[0]
        ));
    }
Example #14
0
 /**
  * Populate a Zend_Form SELECT element from a database table
  *
  * @param \Doctrine\ORM\Query $query The query to for the database select
  * @param Zend_Form_Element_Select $element The form element to populate
  * @param string $entity The Doctrine2 entity class to select items from
  * @param string $indexElement The element with which to set the select value attributes with (typically `id`)
  * @param string|array $displayElements If a string, then the database column element to show in the select
  *         dropdown. If an array, the contents of these elements will be concatenated with dashes
  * @param string $orderBy The element to order by
  * @param string $orderDir The order direction
  * @return int The maximum value of the $indexElement (asuming integer!)
  */
 public static function populateSelectFromDatabaseQuery($query, $element, $entity, $indexElement, $displayElements, $orderBy = null, $orderDir = 'ASC')
 {
     if (!is_array($displayElements)) {
         $displayElements = [$displayElements];
     }
     $rows = $query->getResult();
     $options = array('0' => '');
     $maxId = 0;
     foreach ($rows as $r) {
         $text = '';
         foreach ($displayElements as $idx => $de) {
             if (is_array($de)) {
                 switch ($de['type']) {
                     case 'STRING':
                         $str = $r[$idx];
                         break;
                     case 'DATE':
                     case 'TIME':
                     case 'DATETIME':
                         $str = $r[$idx]->format($de['format']);
                         break;
                     default:
                         die('Unhandled type in OSS/Form/Trait/Doctrine2::populateSelectFromDatabaseQuery()');
                 }
             } else {
                 $str = $r[$de];
             }
             $text .= "{$str} - ";
         }
         $text = substr($text, 0, strlen($text) - 3);
         $options[$r[$indexElement]] = $text;
         if ($r[$indexElement] > $maxId) {
             $maxId = $r[$indexElement];
         }
     }
     $element->setMultiOptions($options);
     return $maxId;
 }
Example #15
0
 /**
  * Performs a given database selection and post-processed the results.
  *
  * @param Doctrine\ORM\Query $query       The Query instance to be executed.
  * @param string             $orderBy     The order-by clause to use when retrieving the collection (optional) (default='').
  * @param boolean            $isPaginated Whether the given query uses a paginator or not (optional) (default=false).
  *
  * @return Array with retrieved collection and (for paginated queries) the amount of total records affected.
  */
 public function retrieveCollectionResult(Query $query, $orderBy = '', $isPaginated = false)
 {
     if (!$isPaginated) {
         $result = $query->getResult();
     } else {
         $paginator = new Paginator($query, false);
         $count = count($paginator);
         $result = $paginator;
     }
     if (!$isPaginated) {
         return $result;
     } else {
         return array($result, $count);
     }
 }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function findCollectionBreadcrumbById($id)
 {
     try {
         $sql = sprintf('SELECT n, collectionMeta, defaultMeta
              FROM %s AS p,
                   %s AS n
                     LEFT JOIN n.meta AS collectionMeta
                     LEFT JOIN n.defaultMeta AS defaultMeta
              WHERE p.id = :id AND p.lft > n.lft AND p.rgt < n.rgt
              ORDER BY n.lft', $this->_entityName, $this->_entityName);
         $query = new Query($this->_em);
         $query->setDQL($sql);
         $query->setParameter('id', $id);
         return $query->getResult();
     } catch (NoResultException $ex) {
         return [];
     }
 }
 protected function getOneResult(\Doctrine\ORM\Query $query)
 {
     $result = $query->getResult();
     return isset($result[0]) ? $result[0] : null;
 }
Example #18
0
 public function getResults(\Doctrine\ORM\Query $query, $cacheId = null, $useCache = false)
 {
     $query->useResultCache($useCache, $this->cacheDuration, $cacheId);
     return $query->getResult();
 }
Example #19
0
 /**
  * Processes the result after it was retrieved. In the default configuration, it returns an array result, or
  * if no query fields are specified, it tries to serialize all objects.
  */
 protected function getResult(Query $query)
 {
     if (count($this->getQueryFields()) == 0) {
         $aSerializedResult = array();
         foreach ($query->getResult() as $result) {
             $aSerializedResult[] = $result->serialize();
         }
         return $aSerializedResult;
     } else {
         return $query->getArrayResult();
     }
 }
Example #20
0
 /**
  * @param DBALQueryBuilder|Query $queryBuilder
  *
  * @return int[]
  */
 private function getPostIds($queryBuilder)
 {
     $ids = [];
     if ($queryBuilder instanceof DBALQueryBuilder) {
         foreach ($queryBuilder->execute()->fetchAll() as $post) {
             $ids[] = (int) $post['id'];
         }
     } elseif ($queryBuilder instanceof Query) {
         foreach ($queryBuilder->getResult() as $post) {
             $ids[] = $post->getId();
         }
     }
     return array_unique($ids);
 }
Example #21
0
 public static function doQueryResult(\Doctrine\ORM\Query $query, $resultType)
 {
     switch ($resultType) {
         case ResultType::ArrayType:
             return $query->getArrayResult();
             break;
         case ResultType::ObjectType:
             return $query->getResult();
             break;
         case ResultType::SingleObjectType:
             return $query->getSingleResult();
             break;
         case ResultType::SingleArrayType:
             return $query->getSingleResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
             break;
         default:
             throw new \Exception("Not a valid ResultType.");
     }
 }