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