Pager.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  5. * (c) Jonathan H. Wage <jonwage@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\DoctrineORMAdminBundle\Datagrid;
  11. use Sonata\AdminBundle\Datagrid\Pager as BasePager;
  12. use Doctrine\ORM\Query;
  13. use Doctrine\ORM\QueryBuilder;
  14. /**
  15. * Doctrine pager class.
  16. *
  17. * @author Jonathan H. Wage <jonwage@gmail.com>
  18. */
  19. class Pager extends BasePager
  20. {
  21. protected $queryBuilder = null;
  22. /**
  23. * Returns a query for counting the total results.
  24. *
  25. * @return integer
  26. */
  27. public function computeNbResult()
  28. {
  29. $countQuery = clone $this->getQuery();
  30. if (count($this->getParameters()) > 0) {
  31. $countQuery->setParameters($this->getParameters());
  32. }
  33. $countQuery->select(sprintf('count(DISTINCT %s.%s) as cnt', $countQuery->getRootAlias(), current($this->getCountColumn())));
  34. return $countQuery->getSingleScalarResult();
  35. }
  36. /**
  37. * Get all the results for the pager instance
  38. *
  39. * @param mixed $hydrationMode A hydration mode identifier
  40. * @return array
  41. */
  42. public function getResults($hydrationMode = Query::HYDRATE_OBJECT)
  43. {
  44. return $this->getQuery()->execute(array(), $hydrationMode);
  45. }
  46. /**
  47. * Get the query for the pager.
  48. *
  49. * @return \AdminBundle\Datagrid\ORM\ProxyQuery
  50. */
  51. public function getQuery()
  52. {
  53. return $this->query;
  54. }
  55. public function init()
  56. {
  57. $this->resetIterator();
  58. $this->setNbResults($this->computeNbResult());
  59. $this->getQuery()->setFirstResult(null);
  60. $this->getQuery()->setMaxResults(null);
  61. if (count($this->getParameters()) > 0) {
  62. $this->getQuery()->setParameters($this->getParameters());
  63. }
  64. if (0 == $this->getPage() || 0 == $this->getMaxPerPage() || 0 == $this->getNbResults()) {
  65. $this->setLastPage(0);
  66. } else {
  67. $offset = ($this->getPage() - 1) * $this->getMaxPerPage();
  68. $this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
  69. $this->getQuery()->setFirstResult($offset);
  70. $this->getQuery()->setMaxResults($this->getMaxPerPage());
  71. }
  72. }
  73. }