Passed
Pull Request — 1.x (#58)
by Akihito
06:21 queued 04:07
created

ExtendedPdoAdapter::getSlice()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\AuraSqlModule\Pagerfanta;
6
7
use Aura\Sql\ExtendedPdoInterface;
8
use Pagerfanta\Adapter\AdapterInterface;
9
use PDO;
10
11
use function assert;
12
use function count;
13
use function is_int;
14
use function preg_match;
15
use function preg_replace;
16
use function preg_split;
17
use function strpos;
18
use function strtolower;
19
use function trim;
20
21
use const PHP_EOL;
22
23
class ExtendedPdoAdapter implements AdapterInterface
24
{
25
    /** @var ExtendedPdoInterface */
26
    private $pdo;
27
28
    /** @var string */
29
    private $sql;
30 14
31
    /** @var array<mixed> */
32 14
    private $params;
33 14
34 14
    /**
35 14
     * @param array<mixed> $params
36
     */
37
    public function __construct(ExtendedPdoInterface $pdo, string $sql, array $params)
38
    {
39
        $this->pdo = $pdo;
40 9
        $this->sql = $sql;
41
        $this->params = $params;
42
    }
43 9
44 9
    /**
45
     * {@inheritdoc}
46 1
     *
47 1
     * @phpstan-return positive-int
48
     */
49 1
    public function getNbResults(): int
50
    {
51 8
        // be smart and try to guess the total number of records
52
        $countQuery = $this->rewriteCountQuery($this->sql);
53 2
        if (! $countQuery) {
54 2
            // GROUP BY => fetch the whole result set and count the rows returned
55 2
            $result = $this->pdo->perform($this->sql, $this->params)->fetchAll();
56 2
            $count = ! $result ? 0 : count($result);
57
            goto ret;
58 2
        }
59
60 6
        if ($this->params) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->params of type array<mixed,mixed> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
61
            $count = $this->pdo->fetchValue($countQuery, $this->params);
62 6
            goto ret;
63
        }
64
65
        $count = $this->pdo->fetchValue($countQuery);
66
        ret:
67
        /** @var string $count */
68 6
        $nbResult = ! $count ? 0 : (int) $count;
69
        assert(is_int($nbResult));
70 6
        assert($nbResult > 0);
71 6
72
        return $nbResult;
73 6
    }
74
75
    /**
76
     * {@inheritdoc}
77
     *
78
     * @param int $offset
79 9
     * @param int $length
80
     *
81 9
     * @return array<array<mixed>>
82 9
     */
83 5
    public function getSlice(int $offset, int $length): iterable
84 5
    {
85 5
        $sql = $this->sql . $this->getLimitClause($offset, $length);
86
        $result = $this->pdo->perform($sql, $this->params)->fetchAll(PDO::FETCH_ASSOC);
87
88 5
        return ! $result ? [] : $result;
89
    }
90
91 4
    /**
92 3
     * {@inheritdoc}
93
     */
94
    public function getLimitClause(int $offset, int $length): string
95 1
    {
96
        if ($offset && $length) {
97
            return PHP_EOL . "LIMIT {$length} OFFSET {$offset}";
98
        }
99
100
        if ($length) {
101
            return PHP_EOL . "LIMIT {$length}";
102
        }
103
104
        return '';
105
    }
106
107
    /**
108
     * Return count query
109
     *
110
     * @param string $query
111
     *
112
     * @return string
113
     *
114
     * @see https://github.com/pear/Pager/blob/master/examples/Pager_Wrapper.php
115
     * Taken from pear/pager and modified.
116
     * tested at https://github.com/pear/Pager/blob/80c0e31c8b94f913cfbdeccbe83b63822f42a2f8/tests/pager_wrapper_test.php#L19
117
     * @codeCoverageIgnore
118
     */
119
    public function rewriteCountQuery($query)
120
    {
121
        if (is_int(strpos(strtolower($query), 'union'))) {
0 ignored issues
show
introduced by
The condition is_int(strpos(strtolower($query), 'union')) is always true.
Loading history...
122
            return '';
123
        }
124
125
        if (preg_match('/^\s*SELECT\s+\bDISTINCT\b/is', $query) || preg_match('/\s+GROUP\s+BY\s+/is', $query)) {
126
            return '';
127
        }
128
129
        $openParenthesis = '(?:\()';
130
        $closeParenthesis = '(?:\))';
131
        $subQueryInSelect = $openParenthesis . '.*\bFROM\b.*' . $closeParenthesis;
132
        $pattern = '/(?:.*' . $subQueryInSelect . '.*)\bFROM\b\s+/Uims';
133
        if (preg_match($pattern, $query)) {
134
            return '';
135
        }
136
137
        $subQueryWithLimitOrder = $openParenthesis . '.*\b(LIMIT|ORDER)\b.*' . $closeParenthesis;
138
        $pattern = '/.*\bFROM\b.*(?:.*' . $subQueryWithLimitOrder . '.*).*/Uims';
139
        if (preg_match($pattern, $query)) {
140
            return '';
141
        }
142
143
        $queryCount = preg_replace('/(?:.*)\bFROM\b\s+/Uims', 'SELECT COUNT(*) FROM ', $query, 1);
144
        /** @var array<int> $split */
145
        $split = preg_split('/\s+ORDER\s+BY\s+/is', (string) $queryCount);
146
        [$queryCount] = $split;
147
        /** @var array<int> $split2 */
148
        $split2 = preg_split('/\bLIMIT\b/is', (string) $queryCount);
149
        [$queryCount2] = $split2;
150
151
        return trim((string) $queryCount2);
152
    }
153
}
154