/
Paginator.php
88 lines (73 loc) · 2.53 KB
/
Paginator.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
namespace Nadia\Bundle\PaginatorBundle;
use Nadia\Bundle\PaginatorBundle\Configuration\PaginatorBuilder;
use Nadia\Bundle\PaginatorBundle\Event\BeforeEvent;
use Nadia\Bundle\PaginatorBundle\Event\ItemsEvent;
use Nadia\Bundle\PaginatorBundle\Event\PaginationEvent;
use Nadia\Bundle\PaginatorBundle\Pagination\PaginationInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class Paginator
{
/**
* @var PaginatorBuilder
*/
private $builder;
/**
* @var EventDispatcherInterface
*/
private $eventDispatcher;
/**
* @var BeforeEvent
*/
private $beforeEvent;
/**
* Paginator constructor.
*
* @param PaginatorBuilder $builder
* @param EventDispatcherInterface $eventDispatcher
*/
public function __construct(PaginatorBuilder $builder, EventDispatcherInterface $eventDispatcher)
{
$this->builder = $builder;
$this->eventDispatcher = $eventDispatcher;
$this->beforeEvent = new BeforeEvent($this->builder, $this->eventDispatcher);
$this->eventDispatcher->dispatch('nadia_paginator.before', $this->beforeEvent);
}
/**
* Do the paginate process and generate Pagination instance
*
* @param mixed $target Paginating target, retrieve data from this target instance
* @param int|null $page
* @param int|null $pageSize
*
* @return PaginationInterface
*/
public function paginate($target, $page = null, $pageSize = null)
{
$beforeEvent = $this->beforeEvent;
if (!is_null($page) && is_numeric($page)) {
$beforeEvent->input->setPage((int) $page);
}
if (!is_null($pageSize) && is_numeric($pageSize)) {
$beforeEvent->input->setPageSize((int) $pageSize);
}
$itemsEvent = new ItemsEvent($this->builder, $beforeEvent->input);
$itemsEvent->target =& $target;
$this->eventDispatcher->dispatch('nadia_paginator.items', $itemsEvent);
$paginationEvent = new PaginationEvent($this->builder);
$this->eventDispatcher->dispatch('nadia_paginator.pagination', $paginationEvent);
$pagination = $paginationEvent->pagination;
$pagination->setCount($itemsEvent->count);
$pagination->setItems($itemsEvent->items);
$pagination->setForm($beforeEvent->form);
$pagination->setInput($beforeEvent->input);
return $pagination;
}
/**
* @return PaginatorBuilder
*/
public function getBuilder()
{
return $this->builder;
}
}