1: <?php
2:
3: namespace PHPixie\Paginate;
4:
5: class Pager
6: {
7: protected $loader;
8: protected $pageSize;
9:
10: protected $currentPage = 1;
11: protected $itemCount;
12: protected $pageCount;
13:
14:
15: public function __construct($loader, $pageSize)
16: {
17: $this->loader = $loader;
18: $this->pageSize = $pageSize;
19: }
20:
21: public function pageSize()
22: {
23: return $this->pageSize;
24: }
25:
26: public function currentPage()
27: {
28: return $this->currentPage;
29: }
30:
31: public function setCurrentPage($page)
32: {
33: if(!$this->pageExists($page)) {
34: throw new \PHPixie\Paginate\Exception("Page $page does not exist");
35: }
36:
37: $this->currentPage = $page;
38: }
39:
40: public function pageExists($page)
41: {
42: $this->requireCount();
43:
44: return $page <= $this->pageCount && $page > 0;
45: }
46:
47: public function pageOffsetExists($offset)
48: {
49: return $this->pageExists($this->currentPage + $offset);
50: }
51:
52: public function getPageByOffset($offset)
53: {
54: $page = $this->currentPage + $offset;
55: if($this->pageExists($page)) {
56: return $page;
57: }
58: return null;
59: }
60:
61: public function previousPage()
62: {
63: return $this->getPageByOffset(-1);
64: }
65:
66: public function nextPage()
67: {
68: return $this->getPageByOffset(1);
69: }
70:
71: public function getAdjacentPages($limit)
72: {
73: $this->requireCount();
74: $pageCount = $this->pageCount;
75:
76: if($limit >= $pageCount) {
77: return range(1 , $pageCount);
78: }
79:
80: $start = $this->currentPage - (int) ($limit/2);
81:
82: if($start < 1) {
83: return range(1, $limit);
84: }
85:
86: if($start + $limit - 1 > $pageCount) {
87: return range($pageCount - $limit + 1, $pageCount);
88: }
89:
90: $end = $start + $limit - 1;
91:
92: if($start > $end) {
93: return array();
94: }
95:
96: return range($start, $end);
97: }
98:
99: public function itemCount()
100: {
101: $this->requireCount();
102: return $this->itemCount;
103: }
104:
105: public function pageCount()
106: {
107: $this->requireCount();
108: return $this->pageCount;
109: }
110:
111: protected function requireCount()
112: {
113: if($this->itemCount === null) {
114: $this->itemCount = $this->loader->getCount();
115: $this->pageCount = (int) ceil($this->itemCount/$this->pageSize);
116: if($this->pageCount === 0) {
117: $this->pageCount = 1;
118: }
119: }
120: }
121:
122: public function getCurrentItems()
123: {
124: $this->requireCount();
125:
126: $offset = $this->pageSize * ($this->currentPage - 1);
127:
128: if($this->currentPage === $this->pageCount) {
129: $limit = $this->itemCount - $offset;
130: }else{
131: $limit = $this->pageSize;
132: }
133:
134: return $this->loader->getItems(
135: $offset,
136: $limit
137: );
138: }
139: }
140: