DbSelect.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. /**
  3. *
  4. * Cube Framework $Id$ AyfDLhYZEYC1elBuhOzNSj7OIO5TeeE92m4ciyI2DvI=
  5. *
  6. * @link http://codecu.be/framework
  7. * @copyright Copyright (c) 2015 CodeCube SRL
  8. * @license http://codecu.be/framework/license Commercial License
  9. *
  10. * @version 1.7
  11. */
  12. /**
  13. * db select pagination adapter
  14. */
  15. namespace Cube\Paginator\Adapter;
  16. use Cube\Db\Select,
  17. Cube\Db\Expr;
  18. class DbSelect implements AdapterInterface
  19. {
  20. /**
  21. *
  22. * the select object
  23. *
  24. * @var \Cube\Db\Select
  25. */
  26. protected $_select;
  27. /**
  28. *
  29. * total number of rows
  30. *
  31. * @var integer
  32. */
  33. protected $_count = null;
  34. /**
  35. *
  36. * class constructor
  37. *
  38. * @param \Cube\Db\Select $select the select object
  39. */
  40. public function __construct(Select $select)
  41. {
  42. $this->_select = $select;
  43. }
  44. /**
  45. *
  46. * returns an array of items for the selected page
  47. *
  48. * @param integer $offset page offset
  49. * @param integer $itemCountPerPage number of items per page
  50. * @return array
  51. */
  52. public function getItems($offset, $itemCountPerPage)
  53. {
  54. $this->_select->limit($itemCountPerPage, $offset);
  55. return $this->_select->query()->fetchAll();
  56. }
  57. /**
  58. *
  59. * return the number of rows in the result set
  60. * TODO: refactor for UNION and HAVING as this solution is slower
  61. *
  62. * @return integer
  63. */
  64. public function count()
  65. {
  66. if ($this->_count === null) {
  67. $select = clone $this->_select;
  68. $union = $select->getPart(Select::UNION);
  69. $having = $select->getPart(Select::HAVING);
  70. if (count($union) > 0 || count($having) > 0) {
  71. $stmt = $select->query();
  72. $this->_count = count($stmt->fetchAll());
  73. }
  74. else {
  75. $select->reset(Select::COLUMNS)
  76. ->reset(Select::ORDER);
  77. $select->columns(array('nb_rows' => new Expr('count(*)')));
  78. $stmt = $select->query();
  79. if ($select->getPart(Select::GROUP)) {
  80. $this->_count = count($stmt->fetchAll());
  81. }
  82. else {
  83. $this->_count = (integer) $stmt->fetchColumn('nb_rows');
  84. }
  85. }
  86. }
  87. return $this->_count;
  88. }
  89. }