1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Application; |
4
|
|
|
|
5
|
|
|
use Silex\Application; |
6
|
|
|
use Knp\Component\Pager\Paginator as KnpPaginator; |
7
|
|
|
use Doctrine\ORM\QueryBuilder; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* @author Borut Balažek <[email protected]> |
11
|
|
|
*/ |
12
|
|
|
class Paginator |
13
|
|
|
{ |
14
|
|
|
protected $app; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @param Application $app |
18
|
|
|
*/ |
19
|
|
|
public function __construct(Application $app) |
20
|
|
|
{ |
21
|
|
|
$this->app = $app; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param mixed $data |
26
|
|
|
* @param int $currentPage |
27
|
|
|
* @param int $limitPerPage |
28
|
|
|
* @param array $options |
29
|
|
|
* |
30
|
|
|
* @throws \Exception If searchFields $option key is set without the $data variable being type QueryBuilder. |
31
|
|
|
*/ |
32
|
|
|
public function paginate($data, $currentPage = 1, $limitPerPage = 10, $options = array()) |
33
|
|
|
{ |
34
|
|
|
$paginator = new KnpPaginator(); |
35
|
|
|
|
36
|
|
|
if ($currentPage === null) { |
37
|
|
|
$currentPage = 1; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
if (!isset($options['searchParameter'])) { |
41
|
|
|
$options['searchParameter'] = 'search'; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
// Temporary solution. We'll try to figure out a better one soon! |
45
|
|
|
$searchFields = isset($options['searchFields']) |
46
|
|
|
? $options['searchFields'] |
47
|
|
|
: false |
48
|
|
|
; |
49
|
|
|
|
50
|
|
|
$searchValue = $this->app['request']->query->get( |
51
|
|
|
$options['searchParameter'], |
52
|
|
|
false |
53
|
|
|
); |
54
|
|
|
|
55
|
|
|
if ($searchFields && !($data instanceof QueryBuilder)) { |
56
|
|
|
throw new \Exception('If you want to use search, you MUST use the QueryBuilder!'); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
if ($searchFields && $searchValue) { |
60
|
|
|
if (is_string($searchFields)) { |
61
|
|
|
$searchFields = explode(',', $searchFields); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
foreach ($searchFields as $searchFieldKey => $searchField) { |
65
|
|
|
$data |
66
|
|
|
->orWhere($searchField.' LIKE ?'.$searchFieldKey) |
67
|
|
|
->setParameter($searchFieldKey, '%'.$searchValue.'%') |
68
|
|
|
; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return $paginator->paginate( |
73
|
|
|
$data, |
74
|
|
|
$currentPage, |
75
|
|
|
$limitPerPage, |
76
|
|
|
$options |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|