This repository has been archived by the owner on Jan 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PaginationListener.php
66 lines (54 loc) · 1.91 KB
/
PaginationListener.php
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
<?php
namespace Carew\Plugin\Pagination;
use Carew\Event\Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class PaginationListener implements EventSubscriberInterface
{
private $twig;
private $maxPerPage;
public function __construct(\Twig_Environment $twig, $maxPerPage = 10)
{
$this->twig = $twig;
$this->maxPerPage = $maxPerPage;
}
public function onDocument($event)
{
$indexes = $event->getSubject();
$indexesTmp = array();
foreach ($indexes as $index) {
if ('html' === pathinfo($index->getPath(), PATHINFO_EXTENSION)) {
$vars = $index->getVars();
$posts = $vars['posts'];
$nbPosts = count($posts);
$this->twig->addGlobal('nb_posts', $nbPosts);
if ($this->maxPerPage >= $nbPosts) {
return;
}
foreach (array_chunk($posts, $this->maxPerPage) as $page => $chunk) {
$newIndex = clone $index;
$varsTmp = array_replace($vars, array(
'posts' => $chunk,
'page' => $page + 1,
));
$newIndex->setVars($varsTmp);
if (0 === $page) {
$newIndex->setPath('index.html');
} else {
$newIndex->setPath(sprintf('page/%s.html', $page + 1));
}
$indexesTmp[$newIndex->getPath()] = $newIndex;
}
}
}
$this->twig->addGlobal('posts_pagination', $indexesTmp);
$event->setSubject(array_merge($indexes, $indexesTmp));
}
public static function getSubscribedEvents()
{
return array(
Events::INDEXES => array(
array('onDocument', 1024),
),
);
}
}