|
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 Pagerfanta\Adapter\AdapterInterface; |
|
10
|
|
|
use PDO; |
|
11
|
|
|
use PDOStatement; |
|
12
|
|
|
|
|
13
|
|
|
use function assert; |
|
14
|
|
|
use function call_user_func; |
|
15
|
|
|
use function is_array; |
|
16
|
|
|
use function is_int; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @template T |
|
20
|
|
|
* @implements AdapterInterface<T> |
|
21
|
|
|
*/ |
|
22
|
|
|
class AuraSqlQueryAdapter implements AdapterInterface |
|
23
|
|
|
{ |
|
24
|
|
|
private ExtendedPdoInterface $pdo; |
|
25
|
|
|
private SelectInterface $select; |
|
26
|
|
|
|
|
27
|
|
|
/** @var callable */ |
|
28
|
|
|
private $countQueryBuilderModifier; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @param callable $countQueryBuilderModifier a callable to modifier the query builder to count |
|
32
|
|
|
*/ |
|
33
|
|
|
public function __construct(ExtendedPdoInterface $pdo, SelectInterface $select, callable $countQueryBuilderModifier) |
|
34
|
|
|
{ |
|
35
|
|
|
$this->pdo = $pdo; |
|
36
|
|
|
$this->select = clone $select; |
|
37
|
|
|
$this->countQueryBuilderModifier = $countQueryBuilderModifier; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* {@inheritdoc} |
|
42
|
|
|
*/ |
|
43
|
|
|
public function getNbResults(): int |
|
44
|
|
|
{ |
|
45
|
|
|
$select = $this->prepareCountQueryBuilder(); |
|
46
|
|
|
$sql = $select->getStatement(); |
|
47
|
|
|
$sth = $this->pdo->prepare($sql); |
|
48
|
|
|
assert($sth instanceof PDOStatement); |
|
49
|
|
|
$sth->execute($this->select->getBindValues()); |
|
50
|
|
|
$result = $sth->fetchColumn(); |
|
51
|
|
|
$nbResults = (int) $result; |
|
52
|
|
|
assert($nbResults >= 0); |
|
53
|
|
|
assert(is_int($nbResults)); |
|
54
|
|
|
|
|
55
|
|
|
return $nbResults; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* {@inheritdoc} |
|
60
|
|
|
* |
|
61
|
|
|
* @return iterable<array-key, mixed> |
|
62
|
|
|
*/ |
|
63
|
|
|
public function getSlice(int $offset, int $length): iterable |
|
64
|
|
|
{ |
|
65
|
|
|
$select = clone $this->select; |
|
66
|
|
|
$sql = $select |
|
67
|
|
|
->offset($offset) |
|
68
|
|
|
->limit($length) |
|
69
|
|
|
->getStatement(); |
|
70
|
|
|
$sth = $this->pdo->prepare($sql); |
|
71
|
|
|
assert($sth instanceof PDOStatement); |
|
72
|
|
|
$sth->execute($this->select->getBindValues()); |
|
73
|
|
|
$result = $sth->fetchAll(PDO::FETCH_ASSOC); |
|
74
|
|
|
assert(is_array($result)); |
|
75
|
|
|
|
|
76
|
|
|
return $result; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
private function prepareCountQueryBuilder(): SelectInterface |
|
80
|
|
|
{ |
|
81
|
|
|
$select = clone $this->select; |
|
82
|
|
|
call_user_func($this->countQueryBuilderModifier, $select); |
|
83
|
|
|
|
|
84
|
|
|
return $select; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|