blob: c9ef0a265e79b2e1443823d2da531b6fe840828b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
<?php
/* Icinga DB Web | (c) 2021 Icinga GmbH | GPLv2 */
namespace Icinga\Module\Icingadb\Common;
use Generator;
use Icinga\Module\Icingadb\Widget\ItemList\PageSeparatorItem;
use Icinga\Module\Icingadb\Widget\ShowMore;
use ipl\Orm\ResultSet;
use ipl\Web\Url;
trait LoadMore
{
/** @var int */
protected $pageSize;
/** @var int */
protected $pageNumber;
/** @var Url */
protected $loadMoreUrl;
/**
* Set the page size
*
* @param int $size
*
* @return $this
*/
public function setPageSize(int $size): self
{
$this->pageSize = $size;
return $this;
}
/**
* Set the page number
*
* @param int $number
*
* @return $this
*/
public function setPageNumber(int $number): self
{
$this->pageNumber = $number;
return $this;
}
/**
* Set the url to fetch more items
*
* @param Url $url
*
* @return $this
*/
public function setLoadMoreUrl(Url $url): self
{
$this->loadMoreUrl = $url;
return $this;
}
/**
* Iterate over the given data
*
* Add the page separator and the "LoadMore" button at the desired position
*
* @param ResultSet $result
*
* @return Generator
*/
protected function getIterator(ResultSet $result): Generator
{
$count = 0;
$pageNumber = $this->pageNumber ?: 1;
if ($pageNumber > 1) {
$this->add(new PageSeparatorItem($pageNumber));
}
foreach ($result as $data) {
$count++;
if ($count % $this->pageSize === 0) {
$pageNumber++;
} elseif ($count > $this->pageSize && $count % $this->pageSize === 1) {
$this->add(new PageSeparatorItem($pageNumber));
}
yield $data;
}
if ($count > 0 && $this->loadMoreUrl !== null) {
$showMore = (new ShowMore(
$result,
$this->loadMoreUrl->setParam('page', $pageNumber)
->setAnchor('page-' . ($pageNumber))
))
->setLabel(t('Load More'))
->setAttribute('data-no-icinga-ajax', true);
$this->add($showMore->setTag('li')->addAttributes(['class' => 'list-item']));
}
}
}
|