AuraSqlQueryAdapter::getSlice()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 1
eloc 11
c 2
b 0
f 1
nc 1
nop 2
dl 0
loc 14
rs 9.9
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
    /** @param callable $countQueryBuilderModifier a callable to modifier the query builder to count */
31
    public function __construct(ExtendedPdoInterface $pdo, SelectInterface $select, callable $countQueryBuilderModifier)
32
    {
33
        $this->pdo = $pdo;
34
        $this->select = clone $select;
35
        $this->countQueryBuilderModifier = $countQueryBuilderModifier;
36
    }
37
38
    /**
39
     * {@inheritDoc}
40
     */
41
    public function getNbResults(): int
42
    {
43
        $select = $this->prepareCountQueryBuilder();
44
        $sql = $select->getStatement();
45
        $sth = $this->pdo->prepare($sql);
46
        assert($sth instanceof PDOStatement);
47
        $sth->execute($this->select->getBindValues());
48
        $result = $sth->fetchColumn();
49
        $nbResults = (int) $result;
50
        assert($nbResults >= 0);
51
        assert(is_int($nbResults));
52
53
        return $nbResults;
54
    }
55
56
    /**
57
     * {@inheritDoc}
58
     *
59
     * @return iterable<array-key, mixed>
60
     */
61
    public function getSlice(int $offset, int $length): iterable
62
    {
63
        $select = clone $this->select;
64
        $sql = $select
65
            ->offset($offset)
66
            ->limit($length)
67
            ->getStatement();
68
        $sth = $this->pdo->prepare($sql);
69
        assert($sth instanceof PDOStatement);
70
        $sth->execute($this->select->getBindValues());
71
        $result = $sth->fetchAll(PDO::FETCH_ASSOC);
72
        assert(is_array($result));
73
74
        return $result;
75
    }
76
77
    private function prepareCountQueryBuilder(): SelectInterface
78
    {
79
        $select = clone $this->select;
80
        call_user_func($this->countQueryBuilderModifier, $select);
81
82
        return $select;
83
    }
84
}
85