1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Zenstruck\Porpaginas\Doctrine; |
4
|
|
|
|
5
|
|
|
use Doctrine\ORM\Query; |
6
|
|
|
use Doctrine\ORM\QueryBuilder; |
7
|
|
|
use Doctrine\ORM\Tools\Pagination\Paginator; |
8
|
|
|
use Zenstruck\Porpaginas\Callback\CallbackPage; |
9
|
|
|
use Zenstruck\Porpaginas\Result; |
10
|
|
|
|
11
|
|
|
final class ORMQueryResult implements Result |
12
|
|
|
{ |
13
|
|
|
private $query; |
14
|
|
|
private $fetchCollection; |
15
|
|
|
private $count; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @param Query|QueryBuilder $query |
19
|
|
|
* @param bool $fetchCollection |
20
|
|
|
*/ |
21
|
12 |
|
public function __construct($query, $fetchCollection = true) |
22
|
|
|
{ |
23
|
12 |
|
if ($query instanceof QueryBuilder) { |
24
|
6 |
|
$query = $query->getQuery(); |
25
|
6 |
|
} |
26
|
|
|
|
27
|
12 |
|
$this->query = $query; |
28
|
12 |
|
$this->fetchCollection = $fetchCollection; |
29
|
12 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* {@inheritdoc} |
33
|
|
|
*/ |
34
|
|
|
public function take($offset, $limit) |
35
|
|
|
{ |
36
|
8 |
|
$results = function ($offset, $limit) { |
37
|
8 |
|
return iterator_to_array($this->createPaginator($offset, $limit)); |
38
|
8 |
|
}; |
39
|
|
|
|
40
|
8 |
|
return new CallbackPage($results, [$this, 'count'], $offset, $limit); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* {@inheritdoc} |
45
|
|
|
*/ |
46
|
4 |
|
public function count() |
47
|
|
|
{ |
48
|
4 |
|
if (null !== $this->count) { |
49
|
|
|
return $this->count; |
50
|
|
|
} |
51
|
|
|
|
52
|
4 |
|
return $this->count = count($this->createPaginator(0, 1)); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* {@inheritdoc} |
57
|
|
|
*/ |
58
|
2 |
|
public function getIterator() |
59
|
|
|
{ |
60
|
2 |
|
return $this->query->iterate(); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param int $offset |
65
|
|
|
* @param int $limit |
66
|
|
|
* |
67
|
|
|
* @return Paginator |
68
|
|
|
*/ |
69
|
10 |
|
private function createPaginator($offset, $limit) |
70
|
|
|
{ |
71
|
10 |
|
$query = clone $this->query; |
72
|
10 |
|
$query->setParameters($this->query->getParameters()); |
73
|
|
|
|
74
|
10 |
|
foreach ($this->query->getHints() as $name => $value) { |
75
|
|
|
$query->setHint($name, $value); |
76
|
10 |
|
} |
77
|
|
|
|
78
|
10 |
|
$query->setFirstResult($offset)->setMaxResults($limit); |
79
|
|
|
|
80
|
10 |
|
return new Paginator($query, $this->fetchCollection); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|