|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Ray\AuraSqlModule\Pagerfanta; |
|
6
|
|
|
|
|
7
|
|
|
use Aura\Sql\ExtendedPdoInterface; |
|
8
|
|
|
use Aura\SqlQuery\Common\SelectInterface; |
|
9
|
|
|
use Override; |
|
10
|
|
|
use Pagerfanta\Adapter\AdapterInterface; |
|
11
|
|
|
use PDO; |
|
12
|
|
|
use PDOStatement; |
|
13
|
|
|
|
|
14
|
|
|
use function assert; |
|
15
|
|
|
use function call_user_func; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @template T |
|
19
|
|
|
* @implements AdapterInterface<T> |
|
20
|
|
|
*/ |
|
21
|
|
|
final class AuraSqlQueryAdapter implements AdapterInterface |
|
22
|
|
|
{ |
|
23
|
|
|
private readonly SelectInterface $select; |
|
24
|
|
|
|
|
25
|
|
|
/** @var callable */ |
|
26
|
|
|
private $countQueryBuilderModifier; |
|
27
|
|
|
|
|
28
|
|
|
/** @param callable $countQueryBuilderModifier a callable to modifier the query builder to count */ |
|
29
|
|
|
public function __construct(private readonly ExtendedPdoInterface $pdo, SelectInterface $select, callable $countQueryBuilderModifier) |
|
30
|
|
|
{ |
|
31
|
|
|
$this->select = clone $select; |
|
|
|
|
|
|
32
|
|
|
$this->countQueryBuilderModifier = $countQueryBuilderModifier; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* {@inheritDoc} |
|
37
|
|
|
*/ |
|
38
|
|
|
#[Override] |
|
39
|
|
|
public function getNbResults(): int |
|
40
|
10 |
|
{ |
|
41
|
|
|
$select = $this->prepareCountQueryBuilder(); |
|
42
|
10 |
|
$sql = $select->getStatement(); |
|
43
|
10 |
|
$sth = $this->pdo->prepare($sql); |
|
44
|
10 |
|
assert($sth instanceof PDOStatement); |
|
45
|
10 |
|
$sth->execute($this->select->getBindValues()); |
|
46
|
|
|
$result = $sth->fetchColumn(); |
|
47
|
|
|
$nbResults = (int) $result; |
|
48
|
|
|
assert($nbResults >= 0); |
|
49
|
|
|
|
|
50
|
9 |
|
return $nbResults; |
|
51
|
|
|
} |
|
52
|
9 |
|
|
|
53
|
9 |
|
/** |
|
54
|
9 |
|
* {@inheritDoc} |
|
55
|
9 |
|
* |
|
56
|
9 |
|
* @return iterable<array-key, mixed> |
|
57
|
|
|
*/ |
|
58
|
9 |
|
#[Override] |
|
59
|
|
|
public function getSlice(int $offset, int $length): iterable |
|
60
|
|
|
{ |
|
61
|
|
|
$select = clone $this->select; |
|
62
|
|
|
$sql = $select |
|
63
|
|
|
->offset($offset) |
|
64
|
9 |
|
->limit($length) |
|
65
|
|
|
->getStatement(); |
|
66
|
9 |
|
$sth = $this->pdo->prepare($sql); |
|
67
|
|
|
assert($sth instanceof PDOStatement); |
|
68
|
9 |
|
$sth->execute($this->select->getBindValues()); |
|
69
|
9 |
|
|
|
70
|
9 |
|
return $sth->fetchAll(PDO::FETCH_ASSOC); |
|
71
|
9 |
|
} |
|
72
|
9 |
|
|
|
73
|
9 |
|
private function prepareCountQueryBuilder(): SelectInterface |
|
74
|
|
|
{ |
|
75
|
9 |
|
$select = clone $this->select; |
|
76
|
|
|
call_user_func($this->countQueryBuilderModifier, $select); |
|
77
|
|
|
|
|
78
|
9 |
|
return $select; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|