ArrayPagination.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace AdminAddonUserManager\Pagination;
  3. use AdminAddonUserManager\Pagination\Pagination;
  4. class ArrayPagination implements Pagination {
  5. protected $data;
  6. protected $rowsPerPage;
  7. protected $page;
  8. private $rowsCount = null;
  9. private $slicedData = null;
  10. public function __construct($data, $rowsPerPage = 10) {
  11. $this->data = $data;
  12. $this->rowsPerPage = $rowsPerPage;
  13. $this->page = 1;
  14. }
  15. public function paginate($page) {
  16. if ($page > $this->getPagesCount()) {
  17. $page = $page;
  18. }
  19. if ($page < 1) {
  20. $page = 1;
  21. }
  22. $this->page = $page;
  23. $this->slicedData = null;
  24. }
  25. public function getRowsPerPage() {
  26. return $this->rowsPerPage;
  27. }
  28. public function getRowsCount() {
  29. if ($this->rowsCount !== null) {
  30. return $this->rowsCount;
  31. }
  32. return $this->rowsCount = count($this->data);
  33. }
  34. public function getCurrentPage() {
  35. return $this->page;
  36. }
  37. public function getPagesCount() {
  38. return ceil($this->getRowsCount() / $this->getRowsPerPage());
  39. }
  40. public function getStartOffset() {
  41. return ($this->getCurrentPage() - 1) * $this->getRowsPerPage();
  42. }
  43. public function getEndOffset() {
  44. $endOffset = $this->getStartOffset() + $this->getRowsPerPage();
  45. if ($endOffset > $this->getRowsCount()) {
  46. $endOffset = $this->getRowsCount();
  47. }
  48. return $endOffset;
  49. }
  50. public function getPaginatedRowsCount() {
  51. return $this->getEndOffset() - $this->getStartOffset();
  52. }
  53. public function getPaginatedRows() {
  54. if ($this->slicedData !== null) {
  55. return $this->slicedData;
  56. }
  57. return $this->slicedData = array_slice($this->data, $this->getStartOffset(), $this->getRowsPerPage());
  58. }
  59. }