Datagrid.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  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\AdminBundle\Datagrid;
  11. use Sonata\AdminBundle\Datagrid\PagerInterface;
  12. use Sonata\AdminBundle\Filter\FilterInterface;
  13. class Datagrid implements DatagridInterface
  14. {
  15. /**
  16. *
  17. * The filter instances
  18. * @var array
  19. */
  20. protected $filters = array();
  21. protected $values;
  22. protected $columns;
  23. protected $pager;
  24. protected $bound = false;
  25. public function __construct($query, ListCollection $columns, PagerInterface $pager, array $values = array())
  26. {
  27. $this->pager = $pager;
  28. $this->query = $query;
  29. $this->values = $values;
  30. $this->columns = $columns;
  31. }
  32. public function getPager()
  33. {
  34. return $this->pager;
  35. }
  36. public function getResults()
  37. {
  38. $this->buildPager();
  39. return $this->pager->getResults();
  40. }
  41. public function buildPager()
  42. {
  43. if($this->bound) {
  44. return;
  45. }
  46. foreach ($this->getFilters() as $name => $filter) {
  47. $filter->apply(
  48. $this->query,
  49. isset($this->values[$name]) ? $this->values[$name] : null
  50. );
  51. }
  52. $this->pager->setPage(isset($this->values['_page']) ? $this->values['_page'] : 1);
  53. $this->pager->setQuery($this->query);
  54. $this->pager->init();
  55. $this->bound = true;
  56. }
  57. public function addFilter(FilterInterface $filter)
  58. {
  59. return $this->filters[$filter->getName()] = $filter;
  60. }
  61. public function getFilters()
  62. {
  63. return $this->filters;
  64. }
  65. public function getValues()
  66. {
  67. return $this->values;
  68. }
  69. public function getColumns()
  70. {
  71. return $this->columns;
  72. }
  73. }