1 | <?php |
||
22 | class PaginationAdapter extends AbstractAdapter |
||
23 | { |
||
24 | |||
25 | /** |
||
26 | * @param Page $page |
||
27 | * @param null $filter |
||
28 | * |
||
29 | * @return Page[] |
||
30 | */ |
||
31 | public function transformPage(Page $page, $filter = null) : array { |
||
32 | $config = $page->getAdapterConfig(AdapterFactory::PAGINATION_ADAPTER); |
||
33 | |||
34 | if (!isset($config['variable'])) { |
||
35 | return [$page]; |
||
36 | } |
||
37 | |||
38 | $variable = $config['variable']; |
||
39 | |||
40 | if (!$source = $page->getVariable($variable)) { |
||
41 | throw new VariableNotFoundException("Variable \"{$variable}\" was not set as a data variable for page \"{$page->getId()}\""); |
||
42 | } |
||
43 | |||
44 | $pageId = rtrim($page->getId(), '/'); |
||
45 | $entries = $this->getData($source); |
||
46 | $entriesPerPage = isset($config['entriesPerPage']) ? $config['entriesPerPage'] : 10; |
||
47 | $pageCount = (int) ceil(count($entries) / $entriesPerPage); |
||
48 | |||
49 | $i = 0; |
||
50 | $result = []; |
||
51 | |||
52 | while ($i < $pageCount) { |
||
53 | $pageEntries = array_splice($entries, 0, $entriesPerPage); |
||
54 | $pageIndex = $i + 1; |
||
55 | |||
56 | if ($filter && $pageIndex !== (int) $filter) { |
||
57 | $i += 1; |
||
58 | continue; |
||
59 | } |
||
60 | |||
61 | $url = "{$pageId}/page-{$pageIndex}"; |
||
62 | $pagination = $this->createPagination($pageId, $pageIndex, $pageCount, $entries); |
||
63 | $entriesPage = clone $page; |
||
64 | $entriesPage |
||
65 | ->removeAdapter(AdapterFactory::PAGINATION_ADAPTER) |
||
66 | ->setVariableValue($variable, $pageEntries) |
||
67 | ->setVariableIsParsed($variable) |
||
68 | ->setVariableValue('pagination', $pagination) |
||
69 | ->setVariableIsParsed('pagination') |
||
70 | ->setId($url); |
||
71 | |||
72 | $result[$url] = $entriesPage; |
||
73 | $i += 1; |
||
74 | } |
||
75 | |||
76 | if ($firstPage = reset($result)) { |
||
77 | $mainPage = clone $firstPage; |
||
78 | $mainPage->setId($pageId); |
||
79 | $result[$pageId] = $mainPage; |
||
80 | } |
||
81 | |||
82 | return $result; |
||
83 | } |
||
84 | |||
85 | /** |
||
86 | * Create a pagination array. |
||
87 | * |
||
88 | * @param $pageId |
||
89 | * @param $pageIndex |
||
90 | * @param $pageCount |
||
91 | * @param $entries |
||
92 | * |
||
93 | * @return array |
||
94 | */ |
||
95 | protected function createPagination($pageId, $pageIndex, $pageCount, $entries) { |
||
114 | } |
||
115 |