AuraSqlQueryAdapter::getSlice()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 1
eloc 10
c 2
b 0
f 1
nc 1
nop 2
dl 0
loc 13
rs 9.9332
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;
0 ignored issues
show
Bug introduced by
The property select is declared read-only in Ray\AuraSqlModule\Pagerfanta\AuraSqlQueryAdapter.
Loading history...
32
        $this->countQueryBuilderModifier = $countQueryBuilderModifier;
33
    }
34
35
    /**
36
     * {@inheritDoc}
37
     */
38
    #[Override]
39
    public function getNbResults(): int
40
    {
41
        $select = $this->prepareCountQueryBuilder();
42
        $sql = $select->getStatement();
43
        $sth = $this->pdo->prepare($sql);
44
        assert($sth instanceof PDOStatement);
45
        $sth->execute($this->select->getBindValues());
46
        $result = $sth->fetchColumn();
47
        $nbResults = (int) $result;
48
        assert($nbResults >= 0);
49
50
        return $nbResults;
51
    }
52
53
    /**
54
     * {@inheritDoc}
55
     *
56
     * @return iterable<array-key, mixed>
57
     */
58
    #[Override]
59
    public function getSlice(int $offset, int $length): iterable
60
    {
61
        $select = clone $this->select;
62
        $sql = $select
63
            ->offset($offset)
64
            ->limit($length)
65
            ->getStatement();
66
        $sth = $this->pdo->prepare($sql);
67
        assert($sth instanceof PDOStatement);
68
        $sth->execute($this->select->getBindValues());
69
70
        return $sth->fetchAll(PDO::FETCH_ASSOC);
71
    }
72
73
    private function prepareCountQueryBuilder(): SelectInterface
74
    {
75
        $select = clone $this->select;
76
        call_user_func($this->countQueryBuilderModifier, $select);
77
78
        return $select;
79
    }
80
}
81