Pager.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. *
  41. * @return array
  42. */
  43. public function getResults($hydrationMode = Query::HYDRATE_OBJECT)
  44. {
  45. return $this->getQuery()->execute(array(), $hydrationMode);
  46. }
  47. /**
  48. * Get the query for the pager.
  49. *
  50. * @return \AdminBundle\Datagrid\ORM\ProxyQuery
  51. */
  52. public function getQuery()
  53. {
  54. return $this->query;
  55. }
  56. public function init()
  57. {
  58. $this->resetIterator();
  59. $this->setNbResults($this->computeNbResult());
  60. $this->getQuery()->setFirstResult(null);
  61. $this->getQuery()->setMaxResults(null);
  62. if (count($this->getParameters()) > 0) {
  63. $this->getQuery()->setParameters($this->getParameters());
  64. }
  65. if (0 == $this->getPage() || 0 == $this->getMaxPerPage() || 0 == $this->getNbResults()) {
  66. $this->setLastPage(0);
  67. } else {
  68. $offset = ($this->getPage() - 1) * $this->getMaxPerPage();
  69. $this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
  70. $this->getQuery()->setFirstResult($offset);
  71. $this->getQuery()->setMaxResults($this->getMaxPerPage());
  72. }
  73. }
  74. }