1 | <?php |
||
2 | |||
3 | /** |
||
4 | * This file is part of the miBadger package. |
||
5 | * |
||
6 | * @author Michael Webbers <[email protected]> |
||
7 | * @license http://opensource.org/licenses/Apache-2.0 Apache v2 License |
||
8 | */ |
||
9 | |||
10 | namespace miBadger\Pagination; |
||
11 | |||
12 | /** |
||
13 | * The pagination class. |
||
14 | * |
||
15 | * @since 1.0.0 |
||
16 | */ |
||
17 | class Pagination implements \Countable, \IteratorAggregate |
||
18 | { |
||
19 | const DEFAULT_ITEMS_PER_PAGE = 10; |
||
20 | |||
21 | /** @var mixed[] The items */ |
||
22 | private $items; |
||
23 | |||
24 | /** @var int The number of items */ |
||
25 | private $itemsPerPage; |
||
26 | |||
27 | /** |
||
28 | * Construct a pagination object with the given items en items per page. |
||
29 | * |
||
30 | * @param mixed[] $items |
||
31 | * @param int $itemsPerPage |
||
32 | */ |
||
33 | public function __construct(array $items, $itemsPerPage = self::DEFAULT_ITEMS_PER_PAGE) |
||
34 | 6 | { |
|
35 | $this->items = $items; |
||
36 | 6 | $this->itemsPerPage = $itemsPerPage; |
|
37 | 6 | } |
|
38 | 6 | ||
39 | /** |
||
40 | * {@inheritdoc} |
||
41 | */ |
||
42 | public function count() |
||
43 | 1 | { |
|
44 | return ceil(count($this->items) / $this->itemsPerPage); |
||
45 | 1 | } |
|
46 | |||
47 | /** |
||
48 | * {@inheritdoc} |
||
49 | */ |
||
50 | public function getIterator() |
||
51 | 1 | { |
|
52 | return new \ArrayIterator(array_chunk($this->items, $this->itemsPerPage)); |
||
53 | 1 | } |
|
54 | |||
55 | /** |
||
56 | * Returns the items on the given page number. |
||
57 | * |
||
58 | * @param int $index |
||
59 | * @return mixed[] the items on the given page number. |
||
60 | */ |
||
61 | public function get($index) |
||
62 | 1 | { |
|
63 | return array_slice($this->items, $index * $this->itemsPerPage, $this->itemsPerPage); |
||
64 | 1 | } |
|
65 | |||
66 | /** |
||
67 | * Returns an array containing all of the elements in this pagination object. |
||
68 | * |
||
69 | * @return mixed[] an array containing all of the elements in this pagination object. |
||
70 | */ |
||
71 | public function toArray() |
||
72 | 1 | { |
|
73 | return $this->items; |
||
74 | 1 | } |
|
75 | |||
76 | /** |
||
77 | * Returns the items per page. |
||
78 | * |
||
79 | * @return int the items per page. |
||
80 | */ |
||
81 | public function getItemsPerPage() |
||
82 | 2 | { |
|
83 | return $this->itemsPerPage; |
||
84 | 2 | } |
|
85 | |||
86 | /** |
||
87 | * Returns the items per page. |
||
88 | * |
||
89 | * @param $itemsPerPage = self::DEFAULT_ITEMS_PER_PAGE |
||
0 ignored issues
–
show
Documentation
Bug
introduced
by
![]() |
|||
90 | * @return null |
||
91 | */ |
||
92 | public function setItemsPerPage($itemsPerPage = self::DEFAULT_ITEMS_PER_PAGE) |
||
93 | 1 | { |
|
94 | $this->itemsPerPage = $itemsPerPage; |
||
95 | 1 | } |
|
96 | } |
||
97 |