/** * Realiza a pesquisa paginada * IMPORTANTE: definir o hydration mode em sua repository (QUERY::HYDRATE_ARRAY), pois afeta a performance * @return \StdClass */ public function getGridData($searchQueryMethod = 'searchQuery', $prepareGridRowsMethod = 'prepareGridRows', $hydration_mode = null) { // Busca a query que será utilizada na pesquisa para a grid $query = $this->getService()->{$searchQueryMethod}($this->getDto()); // pagina a ser retornada // quantidade de linhas a serem retornadas por página $rows = $this->getDto()->query->has('rows') ? $this->getDto()->query->get('rows', 20) : $this->getDto()->request->get('rows', 20); $page = $this->getDto()->query->has('page') ? $this->getDto()->query->get('page', 1) : $this->getDto()->request->get('page', 1); $rows = $rows >= 1 ? $rows : 20; //só para evitar divisão por 0 $page = $page >= 1 ? $page : 1; //só para evitar página negativa $start = $page * $rows - $rows; $start = $start >= 0 ? $start : 0; $query->setFirstResult($start)->setMaxResults($rows); if ($hydration_mode) { $query->setHydrationMode($hydration_mode); } $pagination = new Paginator($query, true); // Objeto de resposta $data = new \StdClass(); $data->count = $pagination->count(); $data->itemsPerPage = $rows; $data->page = $page; $data->pageCount = ceil($pagination->count() / $rows); // linhas da resposta - o método abaixo pode (e provavelmente deve) // ser implantado de acordo com as necessidades da aplicação $data->items = $this->{$prepareGridRowsMethod}($pagination); return $data; }
/** * {@inheritDoc} * * @api */ public function getItemCount() { if (null === $this->itemCount) { $this->itemCount = (int) $this->paginator->count(); } return $this->itemCount; }
/** * * @return int */ public function getResultCount() { if ($this->paginator instanceof DoctrinePaginator) { return $this->paginator->count(); } return 0; }
/** * @param Query|QueryBuilder $query * @param int $limit * @param int $currentPage */ public function __construct($query, $limit, $currentPage = 1) { $this->paginator = new DoctrinePaginator($query); $this->totalCount = $this->paginator->count(); $this->limit = $limit; $this->pagesCount = (int) ceil($this->totalCount / $this->limit); if ($this->pagesCount > 0 && $currentPage > $this->pagesCount) { $currentPage = $this->pagesCount; } $this->currentPage = $currentPage; $this->paginator->getQuery()->setFirstResult($this->limit * ($this->currentPage - 1))->setMaxResults($this->limit); $this->query = $query; }
/** * @inheritDoc */ public function paginate($target, $offset, $limit) { $target->setFirstResult($offset)->setMaxResults($limit); $paginator = new Paginator($target); $this->total = $paginator->count(); return $paginator->getIterator(); }
/** * @Route("/{page}", name="vacancy_index", requirements={"page": "\d+"}, defaults={"page" = 1}) */ public function indexAction($page, Request $request) { $page = max(1, $page); $length = 5; $start = ($page - 1) * $length; $filter = new Filter(); $form = $this->createForm(FilterType::class, $filter); $form->handleRequest($request); $locale = $this->getParameter('locale'); /** @var EntityManager $em */ $em = $this->getDoctrine()->getManager(); $builder = $em->createQueryBuilder(); $builder->select(['v', 'd', 'vd'])->from('VacancyBundle:Vacancy', 'v')->join('v.department', 'd')->leftJoin('v.descriptions', 'vd')->leftJoin('vd.language', 'l')->andWhere('l.id = :language OR l.name = :locale')->setParameter('language', $filter->getLanguage())->setParameter('locale', $locale); if ($filter->getDepartment()) { $builder->andWhere('d.id = :department')->setParameter('department', $filter->getDepartment()); } $builder->addOrderBy("d.name", 'ASC')->addOrderBy("l.id", 'DESC')->addOrderBy("vd.name", 'ASC')->addGroupBy("v.id, l.id"); // Group by: hax for getting only row of selected language $builder->setFirstResult($start)->setMaxResults($length); $paginator = new Paginator($builder); $filters = []; foreach ($request->query->getIterator() as $key => $value) { $filters[$key] = $value; } return $this->render('VacancyBundle:vacancy:index.html.twig', ['form' => $form->createView(), 'isValid' => $form->isValid(), 'filter' => $filter, 'data' => $paginator, 'pagination' => ['page' => $page, 'total' => ceil($paginator->count() / $length), 'currentFilters' => $filters]]); }
/** * Lists all Viaggio entities. * * @Route("/", name="travel") * @Method("GET") * @Template("AppBundle:Viaggio:mete-visitate.html.twig") */ public function indexAction() { $this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!'); $em = $this->getDoctrine()->getManager(); $user = $this->container->get('security.context')->getToken()->getUser(); $user_id = $user->getId(); // $entities = $em->getRepository('AppBundle:Viaggio')->findBy(['utente'=>$user, 'salvato'=>true],['id' => 'DESC']); // Limit per page. $limit = 4; $page = $this->getRequest()->query->get("page", 1); $thisPage = $page; $query = $em->createQuery("SELECT viaggio, viaggio.id, viaggio.descrizione, viaggio.meta, viaggio.partenza, viaggio.arrivo, viaggio.periodo, viaggio.salvato, user.id\n FROM AppBundle:Viaggio viaggio\n JOIN AppBundle:User user WHERE (viaggio.utente = {$user_id})\n WHERE viaggio.salvato = true\n ORDER BY viaggio.id DESC")->setFirstResult($limit * ($page - 1))->setMaxResults($limit); // $questo=$query->getResult(); $paginator = new Paginator($query, $fetchJoinCollection = true); $maxPages = ceil($paginator->count() / $limit); // $c = count($paginator); // foreach ($paginator as $post) { // echo $post->getHeadline() . "\n"; // } $birthDate = $user->getDataDiNascita(); $age = null; if ($birthDate != null) { //explode the date to get month, day and year $birthDate = explode("-", $birthDate); //get age from date or birthdate $age = date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? date("Y") - $birthDate[2] - 1 : date("Y") - $birthDate[2]; } $ultimaSalvata = $em->getRepository('AppBundle:Viaggio')->findOneBy(array('utente' => $user->getId(), 'salvato' => true), array('id' => 'DESC')); return array('eta' => $age, 'salvata' => $ultimaSalvata, 'user' => $user, 'maxPages' => $maxPages, 'thisPage' => $thisPage, 'issues' => $paginator->getIterator()); }
/** * (non-PHPdoc) * @see \Neutron\DataGridBundle\DataGrid\DataGridHandlerInterface::buildQuery() */ public function buildQuery() { $qb = $this->dataGrid->getQueryBuilder(); if (!$qb instanceof QueryBuilder) { throw new \InvalidArgumentException('Value must be instance of Doctrine\\ORM\\QueryBuilder.'); } $options = $this->getOptions(); // Is dependant grid ? if ($this->dataGrid->isDependentGrid()) { $qb->setParameter('masterGridRowId', $options['masterGridRowId']); } // Orders the records if ($options['orderBy']) { $qb->addOrderBy($options['orderBy'], $options['sort']); } // Applying search filters if ($options['search'] && !empty($options['filters'])) { $this->applyFilters($qb, $options['filters']); } // dispatch should onQueryBuilderReady event here if (!$this->dataGrid->isSortableEnabled() && $options['page'] && $options['records']) { $qb->setMaxResults($options['records']); $qb->setFirstResult(($options['page'] - 1) * $options['records']); } $this->setQuery($qb->getQuery()); // Getting count $paginator = new Paginator($this->getQuery()); //$paginator->setUseOutputWalkers(false); $this->setCount($paginator->count()); return $this; }
public function getListagem($arrData = array(), $intPage = 1, $intQtdPage = 10) { $queryBuilder = $this->_em->createQueryBuilder(); $queryBuilder->select('PessoaFisica')->addSelect('Login.dsLogin')->from('Application\\Entity\\PessoaFisica', 'PessoaFisica')->innerJoin('Application\\Entity\\Login', 'Login', 'with', 'Login.idPessoaFisica = PessoaFisica.idPessoaFisica')->setMaxResults($intQtdPage)->setFirstResult($intPage * ($intPage - 1))->orderBy('PessoaFisica.dsNome', 'asc'); # bind nome if ($arrData['dsNome']) { $queryBuilder->andWhere($queryBuilder->expr()->like('PessoaFisica.dsNome', ':dsNome'))->setParameter('dsNome', '%' . $arrData['dsNome'] . '%'); } # bind cpf if ($arrData['dsCpf']) { $queryBuilder->andWhere('PessoaFisica.dsCpf = :dsCpf')->setParameter('dsCpf', Format::clearCpfCnpj($arrData['dsCpf'])); } # bind dsEmail if ($arrData['dsEmail']) { $queryBuilder->andWhere('PessoaFisica.dsEmail = :dsEmail')->setParameter('dsEmail', $arrData['dsEmail']); } # bind dsLogin if ($arrData['dsLogin']) { $queryBuilder->andWhere('Login.dsLogin = :dsLogin')->setParameter('dsLogin', $arrData['dsLogin']); } $query = $queryBuilder->getQuery(); $registerPaginator = new Paginator($query); $registerPaginator->setUseOutputWalkers(false); $intCountResult = $registerPaginator->count(); $arrDadosPaginator = array('qtdRegister' => $intCountResult, 'qtdPages' => ceil($intCountResult / $intQtdPage), 'pageActual' => $intPage, 'maxResult' => $intQtdPage, 'register' => $registerPaginator); return $arrDadosPaginator; }
/** * Prepare listing instance from Doctrine ORM Query or QueryBuilder. * * Sets 'order by' only for QueryBuilder. * * @param Query|QueryBuilder * @param boolean * @param boolean * @param boolean * @return self * @see Paginator */ public function setQuery($query, $fetchJoinCollection = false, $appendLimit = true, $appendOrder = true) { if ($query instanceof QueryBuilder) { $order = $this->order(); if ($appendOrder && $order) { if (is_array($order)) { call_user_func_array([$query, 'orderBy'], $order); } else { $query->add('orderBy', $order); } } $query = $query->getQuery(); } if (!$query instanceof Query) { throw \InvalidArgumentException('Instance of Doctrine\\ORM\\Query or Doctrine\\ORM\\QueryBuilder required!'); } if ($appendLimit) { $paginator = new Paginator($query, $fetchJoinCollection); $this->setCount($paginator->count()); $query->setFirstResult($this->offset())->setMaxResults($this->limit()); $this->setItems($paginator); } else { $this->setItems($query->getResult()); } return $this; }
public function paginationToPaginatorORM(\Doctrine\ORM\Tools\Pagination\Paginator $paginator) { $this->setTotal($paginator->count()); $this->paginator = $paginator; $dados = array(self::_TOTAL_RECORDS => $this->getTotalGeral(), self::_RECORDS_FILTERED => $this->getTotalGeral()); $this->outPut = array_merge($this->outPut, $dados); }
/** * @return array * @throws OutOfBoundsException */ public function execute() { $queryBuilder = $this->getData(); $aliases = []; $queryBuilder->resetDQLParts(['select', 'orderBy', 'having']); foreach ($this->getColumns() as $column) { if ($column instanceof Select) { $aliases[] = $column->getAlias(); } } foreach (array_unique($aliases) as $alias) { $queryBuilder->addSelect($alias); } foreach ($this->getSortConditions() as $column => $sortDirection) { /** @noinspection PhpParamsInspection */ $queryBuilder->add('orderBy', new OrderBy($column, $sortDirection), true); } if (null !== $this->first) { $queryBuilder->setFirstResult($this->first); } if (null !== $this->max) { $queryBuilder->setMaxResults($this->max); } $paginator = new Paginator($queryBuilder); $this->resultCount = $paginator->count(); $result = $queryBuilder->getQuery()->getResult(); if ($this->resultCount > 0 && empty($result)) { throw new OutOfBoundsException(); } return $result; }
/** * Calculates total count of query records * Notes: this method do not make any modifications of the given query * * @param Query|SqlQuery $query * * @return integer */ public function getCount($query) { if ($this->useWalker($query)) { if (!$query->contains('DISTINCT')) { $query->setHint(CountWalker::HINT_DISTINCT, false); } $paginator = new Paginator($query); $paginator->setUseOutputWalkers(false); $result = $paginator->count(); } else { if ($query instanceof Query) { $parserResult = QueryUtils::parseQuery($query); $parameterMappings = $parserResult->getParameterMappings(); list($params, $types) = QueryUtils::processParameterMappings($query, $parameterMappings); $statement = $query->getEntityManager()->getConnection()->executeQuery('SELECT COUNT(*) FROM (' . $query->getSQL() . ') AS e', $params, $types); } elseif ($query instanceof SqlQuery) { $countQuery = clone $query->getQueryBuilder(); $statement = $countQuery->resetQueryParts()->select('COUNT(*)')->from('(' . $query->getSQL() . ')', 'e')->execute(); } else { throw new \InvalidArgumentException(sprintf('Expected instance of Doctrine\\ORM\\Query or Oro\\Bundle\\EntityBundle\\ORM\\SqlQuery, "%s" given', is_object($query) ? get_class($query) : gettype($query))); } $result = $statement->fetchColumn(); } return $result ? (int) $result : 0; }
/** * @param int $offset * @param int $limit * @param string|null $status * @return PaginationResult */ public function paginateAll($offset, $limit, $status = null) { $queryBuilder = $this->entityRepository->createQueryBuilder('invoice'); $queryBuilder->innerJoin('invoice.client', 'client'); $queryBuilder->setFirstResult($offset); $queryBuilder->setMaxResults($limit); $queryBuilder->orderBy('invoice.id', 'desc'); switch ($status) { case 'paid': $queryBuilder->andWhere('invoice.payDate IS NOT NULL'); break; case 'late': $queryBuilder->andWhere('invoice.payDate IS NULL'); $queryBuilder->andWhere('invoice.dueDate IS NOT NULL'); $queryBuilder->andWhere('invoice.dueDate < :now'); $queryBuilder->setParameter('now', new DateTime()); break; case 'sent': $queryBuilder->andWhere('invoice.payDate IS NULL'); $queryBuilder->andWhere('invoice.dueDate IS NULL OR invoice.dueDate >= :now'); $queryBuilder->andWhere('invoice.sendDate IS NOT NULL'); $queryBuilder->setParameter('now', new DateTime()); break; case 'draft': $queryBuilder->andWhere('invoice.payDate IS NULL'); $queryBuilder->andWhere('invoice.dueDate IS NULL OR invoice.dueDate >= :now'); $queryBuilder->andWhere('invoice.sendDate IS NULL'); $queryBuilder->setParameter('now', new DateTime()); break; } $paginator = new Paginator($queryBuilder->getQuery(), false); return new PaginationResult($paginator->getIterator(), $paginator->count()); }
/** * {@inheritdoc} */ public function count() { if (null === $this->_count) { return parent::count(); } return $this->_count; }
public function buildCount($query) { // Getting count $paginator = new Paginator($this->getQuery()); //$paginator->setUseOutputWalkers(false); $this->setCount($paginator->count()); return $this; }
public function getTotalCount() : int { $queryBuilder = $this->getQueryBuilder(); $query = $queryBuilder->getQuery(); $query->useQueryCache(true); $query->useResultCache(true); $paginator = new Paginator($query, true); $paginator->setUseOutputWalkers(false); return $paginator->count(); }
public function getListagem($arrData = array(), $intPage = 1, $intQtdPage = 10) { $queryBuilder = $this->_em->createQueryBuilder(); $queryBuilder->select('Empreendimento')->from('Application\\Entity\\Empreendimento', 'Empreendimento')->innerJoin('Application\\Entity\\Municipio', 'Municipio', 'with', 'Municipio.idMunicipio = Empreendimento.idMunicipio')->innerJoin('Application\\Entity\\Estado', 'Estado', 'with', 'Estado.idEstado = Municipio.idEstado')->setMaxResults($intQtdPage)->setFirstResult($intPage * ($intPage - 1))->orderBy('Empreendimento.dsEmpreendimento', 'asc'); $query = $queryBuilder->getQuery(); $registerPaginator = new Paginator($query); $registerPaginator->setUseOutputWalkers(false); $intCountResult = $registerPaginator->count(); $arrDadosPaginator = array('qtdRegister' => $intCountResult, 'qtdPages' => ceil($intCountResult / $intQtdPage), 'pageActual' => $intPage, 'maxResult' => $intQtdPage, 'register' => $registerPaginator); return $arrDadosPaginator; }
/** * @return Job */ public function findAllPublishedOrderedByRecentlyActive(JobSearchFormTypeData $data, $currentPage = 1, $limit = 5) { $query = $this->findAllPublishedOrderedByRecentlyActiveQ($data); // Paginator $paginator = new Paginator($query); $rowsCountTotal = $paginator->count(); $data = $query->setFirstResult($limit * ($currentPage - 1))->setMaxResults($limit)->execute(); // ->getOneOrNullResult() $rowsCountThisPage = count($data); return ['limit' => $limit, 'currentPage' => $currentPage, 'maxPages' => ceil($rowsCountTotal / $limit), 'rowsCountTotal' => $rowsCountTotal, 'rowsCountThisPage' => $rowsCountThisPage, 'data' => $data]; }
/** * {@inheritdoc} */ public function getTotalRows(QueryBuilder $queryBuilder, ColumnCollection $columns) { $builder = clone $queryBuilder; $having = $builder->getDQLPart('having'); if (is_object($having)) { $this->replaceHaving($having, $columns, $builder); } $query = $builder->getQuery(); $paginator = new Paginator($query, true); $paginator->setUseOutputWalkers(false); return $paginator->count(); }
/** * @param Router $router * @param string $routeName * @param array $routeParams * * @return array */ public function getLinkHeader(Router $router, $routeName, $routeParams) { $links = []; $totalPages = ceil($this->resource->count() / $this->perPage); if ($this->page > 1) { $links['first'] = $router->generate($routeName, $routeParams + ['page' => 1]); $links['prev'] = $router->generate($routeName, $routeParams + ['page' => $this->page - 1]); } if ($this->page < $totalPages) { $links['next'] = $router->generate($routeName, $routeParams + ['page' => $this->page + 1]); $links['last'] = $router->generate($routeName, $routeParams + ['page' => $totalPages]); } if (!empty($links)) { $linksHeader = []; foreach ($links as $name => $link) { $linksHeader[] = '<' . $link . '>; rel="' . $name . '"'; } return ['Link' => join(', ', $linksHeader)]; } return []; }
public function dashboardAction(Request $request, Application $app) { $repository = $this->get('orm.em')->getRepository('Gedmo\\Loggable\\Entity\\LogEntry'); $queryBuilder = $repository->createQueryBuilder('log'); $queryBuilder->orderBy('log.loggedAt', 'DESC'); $nbResultsPerPage = 30; $firstResult = ($request->get('page', 1) - 1) * $nbResultsPerPage; $queryBuilder->setFirstResult($firstResult)->setMaxResults($nbResultsPerPage); // $entities = $queryBuilder->getQuery()->getResult(); $entities = new Paginator($queryBuilder->getQuery(), $fetchJoinCollection = false); $routes = array('Entity\\Theme' => 'theme', 'Entity\\Story' => 'story', 'Entity\\Module' => 'module', 'Entity\\Event' => 'event'); return $app['twig']->render('admin/index.html.twig', array('entities' => $entities, 'nbPages' => ceil($entities->count() / $nbResultsPerPage), 'routes' => $routes)); }
/** * {@inheritdoc} */ public function getTotalRows(QueryBuilder $queryBuilder, ColumnCollection $columns) : int { $builder = clone $queryBuilder; $having = $builder->getDQLPart('having'); if (is_object($having)) { $this->replaceHaving($having, $columns, $builder); } $query = $builder->getQuery(); $query->useQueryCache(true); $query->useResultCache(true, 3600, self::RESULT_CACHE_ID); $paginator = new Paginator($query, true); $paginator->setUseOutputWalkers(false); return $paginator->count(); }
public function count() { if ($this->count === null) { if ($this->countQuery) { try { $res = $this->countQuery->execute(); $this->count = $res[0]['c']; } catch (NoResultException $e) { $this->count = 0; } } else { $this->count = parent::count(); } } return $this->count; }
/** * * @param array $arrData * @param integer $intPage * @param integer $intQtdPage * @return Paginator */ public function getListagem($arrData = array(), $intPage = 1, $intQtdPage = 10) { $queryBuilder = $this->_em->createQueryBuilder(); $queryBuilder->select('Perefil')->from('Application\\Entity\\Perfil', 'Perefil')->setFirstResult($intPage * ($intPage - 1))->orderBy('Perefil.noPerfil', 'asc'); # bind nome if ($arrData['noPerfil']) { $queryBuilder->andWhere($queryBuilder->expr()->like('Perfil.dsNome', ':noPerfil'))->setParameter('noPerfil', '%' . $arrData['noPerfil'] . '%'); } # bind situacao if ($arrData['inAtivo'] != '') { $queryBuilder->andWhere('Perefil.inAtivo = :inAtivo')->setParameter('inAtivo', $arrData['inAtivo']); } $query = $queryBuilder->getQuery(); $registerPaginator = new Paginator($query); $registerPaginator->setUseOutputWalkers(false); $intCountResult = $registerPaginator->count(); $arrDadosPaginator = array('qtdRegister' => $intCountResult, 'qtdPages' => ceil($intCountResult / $intQtdPage), 'pageActual' => $intPage, 'maxResult' => $intQtdPage, 'register' => $registerPaginator); return $arrDadosPaginator; }
/** * {@inheritDoc} */ protected function doProxyPaginate() { if (!$this->query) { throw new \RuntimeException('Please enter the query for paginate.'); } $query = $this->query; if ($query instanceof QueryBuilder) { $query = $query->getQuery(); } if (!$query instanceof Query) { throw new InvalidQueryException(sprintf('The query must be Doctrine\\ORM\\Query instance, but "%s" given.', is_object($query) ? get_class($query) : gettype($query))); } $this->storage = $query->setMaxResults($this->limit)->setFirstResult($this->limit * $this->page - $this->limit)->getResult(); if (count($this->storage) > 0) { $doctrinePagination = new Paginator($query); $this->fullCount = $doctrinePagination->count(); unset($doctrinePagination); } else { $this->fullCount = 0; } }
/** * @param QueryBuilder $dql * @param null $limit * @param int $offset 0 * @param null $page * @return array [ * 'total' => total number of records * 'query' => QueryBuilder * ] */ public static function paginateResponse(QueryBuilder &$dql, $limit = null, $offset = 0, $page = null) { if ($page !== null) { $offset = $page !== null && $limit !== null ? $limit * ($page - 1) : null; } $clone = Pagination::cloneQuery($dql); $paginator = new Paginator($dql); $total = $paginator->count(); if ($limit !== null && $offset !== null) { $dql->setFirstResult($offset)->setMaxResults($limit); } $fromAlias = current($dql->getRootAliases()); $result = $dql->select("DISTINCT {$fromAlias}.id")->getQuery()->getArrayResult(); $ids = array_map('current', $result); $clone->getParameters()->clear(); if (count($ids) > 0) { $clone->where($clone->expr()->in("{$fromAlias}.id", $ids)); } else { $clone->where("1=0"); } return array('total' => $total, 'query' => $clone); }
public function apiQuery($qdata, $options = []) { $this->_apiFindParamList = []; $app = App::i(); $findOne = key_exists('findOne', $options) ? $options['findOne'] : false; $counting = key_exists('@count', $qdata); if ($counting) { unset($qdata['@count']); } if (class_exists($this->entityClassName)) { if (!$qdata && !$counting) { $this->apiErrorResponse('no data'); } $class = $this->entityClassName; $entity_properties = array_keys($app->em->getClassMetadata($this->entityClassName)->fieldMappings); $entity_associations = $app->em->getClassMetadata($this->entityClassName)->associationMappings; $entity_metadata = []; $metadata_class = ""; $meta_num = 0; $taxo_num = 0; $dql_joins = ""; $dql_select = ""; $dql_select_joins = ""; if ($class::usesMetadata()) { $metadata_class = $class::getMetadataClassName(); $metadata_class = $class . 'Meta'; $dql_join_template = "\n\tLEFT JOIN e.__metadata {ALIAS} WITH {ALIAS}.key = '{KEY}'\n"; foreach ($app->getRegisteredMetadata($this->entityClassName) as $meta) { $entity_metadata[] = $meta->key; } } if ($class::usesTaxonomies()) { $taxonomies = []; $taxonomies_ids = []; foreach ($app->getRegisteredTaxonomies($class) as $obj) { $taxonomies[] = 'term:' . $obj->slug; $taxonomies_ids['term:' . $obj->slug] = $obj->id; } $dql_join_term_template = "\n\tLEFT JOIN e.__termRelations {ALIAS_TR} LEFT JOIN {ALIAS_TR}.term {ALIAS_T} WITH {ALIAS_T}.taxonomy = {TAXO}\n"; } $keys = []; $append_files_cb = function () { }; $select = ['id']; $select_metadata = []; $order = null; $op = ' AND '; $offset = null; $limit = null; $page = null; $keyword = null; $permissions = null; $dqls = []; foreach ($qdata as $key => $val) { $val = trim($val); if (strtolower($key) == '@select') { $select = explode(',', $val); $_joins = []; foreach ($select as $prop) { if (in_array($prop, $entity_metadata)) { $select_metadata[] = $prop; } elseif (strpos($prop, '.') > 0) { $relation = substr($prop, 0, strpos($prop, '.')); $relation_property = substr($prop, strpos($prop, '.') + 1); if (strpos($relation_property, '.') > 0) { $relation_property = substr($relation_property, 0, strpos($relation_property, '.')); } if (isset($entity_associations[$relation])) { if (!isset($_joins[$relation])) { $_joins[$relation] = []; } $_joins[$relation][] = $relation_property; } } } foreach ($_joins as $j => $props) { $join_id = uniqid($j); $dql_select_joins = " LEFT JOIN e.{$j} {$join_id}"; $dql_select .= ", {$join_id}"; } continue; } elseif (strtolower($key) == '@keyword') { $keyword = $val; continue; } elseif (strtolower($key) == '@permissions') { $permissions = explode(',', $val); continue; } elseif (strtolower($key) == '@order') { $order = $val; continue; } elseif (strtolower($key) == '@or') { $op = ' OR '; continue; } elseif (strtolower($key) == '@offset') { $offset = $val; continue; } elseif (strtolower($key) == '@page') { $page = $val; continue; } elseif (strtolower($key) == '@limit') { $limit = $val; continue; } elseif (strtolower($key) == '@type') { continue; } elseif (strtolower($key) == '@debug') { continue; } elseif (strtolower($key) == '@files' && preg_match('#^\\(([\\w\\., ]+)\\)[ ]*(:[ ]*([\\w, ]+))?#i', $val, $imatch)) { if ($counting) { continue; } // example: // @files=(avatar.smallAvatar,header.header):name,url $cfg = ['files' => explode(',', $imatch[1]), 'props' => key_exists(3, $imatch) ? explode(',', $imatch[3]) : ['url']]; $_join_in = []; foreach ($cfg['files'] as $_f) { if (strpos($_f, '.') > 0) { list($_f_group, $_f_transformation) = explode('.', $_f); $_join_in[] = $_f_group; $_join_in[] = 'img:' . $_f_transformation; } else { $_join_in[] = $_f; } } $_join_in = array_unique($_join_in); $dql_select .= " , files, fparent"; $dql_select_joins .= " LEFT JOIN e.__files files WITH files.group IN ('" . implode("','", $_join_in) . "') LEFT JOIN files.parent fparent"; $extract_data_cb = function ($file, $ipath, $props) { $result = []; if ($ipath) { $path = explode('.', $ipath); foreach ($path as $transformation) { $file = $file->transform($transformation); } } if (is_object($file)) { foreach ($props as $prop) { $result[$prop] = $file->{$prop}; } } return $result; }; $append_files_cb = function (&$result, $entity) use($cfg, $extract_data_cb) { $files = $entity->files; foreach ($cfg['files'] as $im) { $im = trim($im); list($igroup, $ipath) = explode('.', $im, 2) + [null, null]; if (!key_exists($igroup, $files)) { continue; } if (is_array($files[$igroup])) { $result["@files:{$im}"] = []; foreach ($files[$igroup] as $file) { $result["@files:{$im}"][] = $extract_data_cb($file, $ipath, $cfg['props']); } } else { $result["@files:{$im}"] = $extract_data_cb($files[$igroup], $ipath, $cfg['props']); } } }; continue; } if (key_exists($key, $entity_associations) && $entity_associations[$key]['isOwningSide']) { $keys[$key] = 'e.' . $key; } elseif (in_array($key, $entity_properties)) { $keys[$key] = 'e.' . $key; } elseif ($class::usesTypes() && $key === 'type') { $keys[$key] = 'e._type'; } elseif ($class::usesTaxonomies() && in_array($key, $taxonomies)) { $taxo_num++; $tr_alias = "tr{$taxo_num}"; $t_alias = "t{$taxo_num}"; $taxonomy_id = $taxonomies_ids[$key]; $keys[$key] = "{$t_alias}.term"; $dql_joins .= str_replace('{ALIAS_TR}', $tr_alias, str_replace('{ALIAS_T}', $t_alias, str_replace('{TAXO}', $taxonomy_id, $dql_join_term_template))); } elseif ($class::usesMetadata() && in_array($key, $entity_metadata)) { $meta_num++; $meta_alias = "m{$meta_num}"; $keys[$key] = "{$meta_alias}.value"; $dql_joins .= str_replace('{ALIAS}', $meta_alias, str_replace('{KEY}', $key, $dql_join_template)); } elseif ($key[0] != '_' && $key != 'callback') { $this->apiErrorResponse("property {$key} does not exists"); } else { continue; } $dqls[] = $this->_API_find_parseParam($keys[$key], $val); } if ($order) { $new_order = []; foreach (explode(',', $order) as $prop) { $key = trim(preg_replace('#asc|desc#i', '', $prop)); if (key_exists($key, $keys)) { $new_order[] = str_ireplace($key, $keys[$key], $prop); } elseif (in_array($key, $entity_properties)) { $new_order[] = str_ireplace($key, 'e.' . $key, $prop); } elseif (in_array($key, $entity_metadata)) { $meta_num++; $meta_alias = "m{$meta_num}"; $dql_joins .= str_replace('{ALIAS}', $meta_alias, str_replace('{KEY}', $key, $dql_join_template)); $new_order[] = str_replace($key, "{$meta_alias}.value", $prop); } } $order = "ORDER BY " . implode(', ', $new_order); } $dql_where = implode($op, $dqls); if ($metadata_class) { $metadata_class = ", {$metadata_class} m"; } $dql_where = $dql_where ? "WHERE {$dql_where}" : ""; if (in_array('status', $entity_properties)) { $status_where = is_array($permissions) && in_array('view', $permissions) ? 'e.status >= 0' : 'e.status > 0'; $dql_where = $dql_where ? "{$dql_where} AND {$status_where}" : "WHERE {$status_where}"; } if ($keyword) { $repo = $this->repo(); if ($repo->usesKeyword()) { $ids = implode(',', $repo->getIdsByKeyword($keyword)); $dql_where .= $ids ? "AND e.id IN({$ids})" : 'AND e.id < 0'; } } if ($select_metadata) { $dql_select .= ', meta'; $meta_keys = implode("', '", $select_metadata); $dql_select_joins .= " LEFT JOIN e.__metadata meta WITH meta.key IN ('{$meta_keys}')"; } if (in_array('terms', $select)) { $dql_select .= ', termRelations, term'; $dql_select_joins .= " LEFT JOIN e.__termRelations termRelations LEFT JOIN termRelations.term term"; } if (in_array('owner', $select) || array_filter($select, function ($prop) { return substr($prop, 0, 6) == 'owner.'; })) { $dql_select .= ', _owner'; $dql_select_joins .= " LEFT JOIN e.owner _owner"; } // unset sql_select and dql_select_joins if using permissions filters to reduce memory usage if (!$findOne && $permissions) { $dql_select = ''; $dql_select_joins = ''; } $final_dql = "\n SELECT\n e {$dql_select}\n FROM\n {$class} e\n\n {$dql_joins}\n {$dql_select_joins}\n\n {$dql_where}\n\n {$order}"; $result[] = "{$final_dql}"; if ($app->config['app.log.apiDql']) { $app->log->debug("API DQL: " . $final_dql); } $query = $app->em->createQuery($final_dql); if ($app->user->is('superAdmin') && isset($_GET['@debug'])) { if (isset($_GET['@type']) && $_GET['@type'] == 'html') { echo '<pre style="color:red">'; } echo "\nDQL Query:\n"; echo "{$final_dql}\n\n"; echo "DQL params: "; print_r($this->_apiFindParamList); echo "\n\nSQL Query\n"; echo "\n{$query->getSQL()}\n\n"; } // cache if ($app->config['app.useApiCache'] && $this->getApiCacheLifetime()) { $query->useResultCache(true, $this->getApiCacheLifetime()); } $query->setParameters($this->_apiFindParamList); $processEntity = function ($r) use($append_files_cb, $select) { $entity = []; $append_files_cb($entity, $r); foreach ($select as $i => $prop) { $prop = trim($prop); try { if (strpos($prop, '.')) { $props = explode('.', $prop); $current_object = $r; foreach ($props as $pk => $p) { if ($p === 'permissionTo' && $pk === count($props) - 2) { $current_object = $current_object->canUser($props[$pk + 1]); break; } else { $current_object = $current_object->{$p}; if (!is_object($current_object)) { break; } } } $prop_value = $current_object; } else { $prop_value = $r->{$prop}; } if (is_object($prop_value) && $prop_value instanceof \Doctrine\Common\Collections\Collection) { $prop_value = $prop_value->toArray(); } if (strpos($prop, '.')) { $props = explode('.', $prop); $carray =& $entity; for ($i = 0; $i < count($props) - 1; $i++) { $p = $props[$i]; if (!isset($carray[$p])) { $carray[$p] = []; } $carray =& $carray[$p]; } $carray[array_pop($props)] = $prop_value; } else { $entity[$prop] = $prop_value; } } catch (\Exception $e) { } } return $entity; }; if ($findOne) { $query->setFirstResult(0)->setMaxResults(1); $paginator = new Paginator($query, $fetchJoinCollection = true); if (count($paginator)) { $r = $paginator->getIterator()->current(); if ($permissions) { foreach ($permissions as $perm) { $perm = trim($perm); if ($perm[0] === '!') { if ($r->canUser(substr($perm, 1))) { $r = null; break; } } else { if (!$r->canUser($perm)) { $r = null; break; } } } } if ($r) { $entity = $processEntity($r); } } else { $entity = null; } return $entity; } else { if ($permissions) { $rs = $query->getResult(); $result = []; $rs = array_values(array_filter($rs, function ($entity) use($permissions) { foreach ($permissions as $perm) { $perm = trim($perm); if ($perm[0] === '!') { $not = true; $_perm = substr($perm, 1); } else { $not = false; $_perm = $perm; } $can = $entity->canUser($_perm); return $not ? !$can : $can; } return true; })); if (!$page) { $page = 1; } $rs_count = count($rs); if ($page && $limit) { $offset = ($page - 1) * $limit; $rs = array_slice($rs, $offset, $limit); } } else { if ($limit) { if (!$page) { $page = 1; } $offset = ($page - 1) * $limit; $query->setFirstResult($offset)->setMaxResults($limit); $paginator = new Paginator($query, $fetchJoinCollection = true); $rs_count = $paginator->count(); $rs = $paginator->getIterator()->getArrayCopy(); } else { $rs = $query->getResult(); $rs_count = count($rs); } } if ($counting) { return count($rs); } $this->apiAddHeaderMetadata($rs, $rs_count); $result = array_map(function ($entity) use($processEntity) { return $processEntity($entity); }, $rs); return $result; } } }
/** * creates the paginator around the query * @param Query $query */ private function getPaginator(Query $query) { $paginator = new Paginator($query, $fetchJoinCollection = FALSE); $this->maxcount = $paginator->count(); return $paginator; }
/** * Evaluates Paginator attributes. * * @param Request $request Request * @param AnnotationPaginator $annotation Annotation * @param Paginator $paginator Paginator * @param integer $limitPerPage Limit per page * @param integer $page Page */ protected function evaluateAttributes(Request $request, AnnotationPaginator $annotation, Paginator $paginator, $limitPerPage, $page) { if ($annotation->getAttributes()) { $paginatorAttributes = new PaginatorAttributes(); $total = $paginator->count(); $paginatorAttributes->setCurrentPage($page)->setLimitPerPage($limitPerPage)->setTotalElements($total)->setTotalPages(ceil($total / $limitPerPage)); $request->attributes->set(trim($annotation->getAttributes()), $paginatorAttributes); } }