1: <?php
2:
3: namespace Charcoal\Source;
4:
5: use \InvalidArgumentException as InvalidArgumentException;
6:
7: 8: 9:
10: class Pagination implements PaginationInterface
11: {
12: const DEFAULT_PAGE = 0;
13: const DEFAULT_NUM_PER_PAGE = 0;
14:
15: 16: 17:
18: protected $page = self::DEFAULT_PAGE;
19: 20: 21:
22: protected $numPerPage = self::DEFAULT_NUM_PER_PAGE;
23:
24: 25: 26: 27:
28: public function setData(array $data)
29: {
30: if (isset($data['page'])) {
31: $this->setPage($data['page']);
32: }
33: if (isset($data['num_per_page'])) {
34: $this->setNumPerPage($data['num_per_page']);
35: }
36: return $this;
37: }
38:
39: 40: 41: 42: 43:
44: public function setPage($page)
45: {
46: if (!is_numeric($page)) {
47: throw new InvalidArgumentException(
48: 'Page number needs to be numeric.'
49: );
50: }
51: $page = (int)$page;
52: if ($page < 0) {
53: throw new InvalidArgumentException(
54: 'Page number needs to be >= 0.'
55: );
56: }
57: $this->page = $page;
58: return $this;
59: }
60:
61: 62: 63:
64: public function page()
65: {
66: return $this->page;
67: }
68:
69: 70: 71: 72: 73:
74: public function setNumPerPage($num)
75: {
76: if (!is_numeric($num)) {
77: throw new InvalidArgumentException(
78: 'Num-per-page needs to be numeric.'
79: );
80: }
81: $num = (int)$num;
82: if ($num < 0) {
83: throw new InvalidArgumentException(
84: 'Num-per-page needs to be >= 0.'
85: );
86: }
87:
88: $this->numPerPage = $num;
89: return $this;
90: }
91:
92: 93: 94:
95: public function numPerPage()
96: {
97: return $this->numPerPage;
98: }
99:
100: 101: 102:
103: public function first()
104: {
105: $page = $this->page();
106: $numPerPage = $this->numPerPage();
107: return max(0, (($page-1)*$numPerPage));
108: }
109:
110: 111: 112: 113:
114: public function last()
115: {
116: $first = $this->first();
117: $numPerPage = $this->numPerPage();
118: return ($first + $numPerPage);
119: }
120: }
121: