Passed
Pull Request — 1.x (#58)
by Akihito
04:19 queued 02:48
created

ExtendedPdoAdapter::getNbResults()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
eloc 14
c 3
b 0
f 0
nc 8
nop 0
dl 0
loc 24
ccs 12
cts 12
cp 1
crap 5
rs 9.4888
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
     * @SuppressWarnings(PHPMD.GotoStatement)
49 1
     */
50
    public function getNbResults(): int
51 8
    {
52
        // be smart and try to guess the total number of records
53 2
        $countQuery = $this->rewriteCountQuery($this->sql);
54 2
        if (! $countQuery) {
55 2
            // GROUP BY => fetch the whole result set and count the rows returned
56 2
            $result = $this->pdo->perform($this->sql, $this->params)->fetchAll();
57
            $count = ! $result ? 0 : count($result);
58 2
            goto ret;
59
        }
60 6
61
        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...
62 6
            $count = $this->pdo->fetchValue($countQuery, $this->params);
63
            goto ret;
64
        }
65
66
        $count = $this->pdo->fetchValue($countQuery);
67
        ret:
68 6
        /** @var string $count */
69
        $nbResult = ! $count ? 0 : (int) $count;
70 6
        assert(is_int($nbResult));
71 6
        assert($nbResult > 0);
72
73 6
        return $nbResult;
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     *
79 9
     * @param int $offset
80
     * @param int $length
81 9
     *
82 9
     * @return array<array<mixed>>
83 5
     */
84 5
    public function getSlice(int $offset, int $length): iterable
85 5
    {
86
        $sql = $this->sql . $this->getLimitClause($offset, $length);
87
        $result = $this->pdo->perform($sql, $this->params)->fetchAll(PDO::FETCH_ASSOC);
88 5
89
        return ! $result ? [] : $result;
90
    }
91 4
92 3
    /**
93
     * {@inheritdoc}
94
     */
95 1
    public function getLimitClause(int $offset, int $length): string
96
    {
97
        if ($offset && $length) {
98
            return PHP_EOL . "LIMIT {$length} OFFSET {$offset}";
99
        }
100
101
        if ($length) {
102
            return PHP_EOL . "LIMIT {$length}";
103
        }
104
105
        return '';
106
    }
107
108
    /**
109
     * Return count query
110
     *
111
     * @param string $query
112
     *
113
     * @return string
114
     *
115
     * @see https://github.com/pear/Pager/blob/master/examples/Pager_Wrapper.php
116
     * Taken from pear/pager and modified.
117
     * tested at https://github.com/pear/Pager/blob/80c0e31c8b94f913cfbdeccbe83b63822f42a2f8/tests/pager_wrapper_test.php#L19
118
     * @codeCoverageIgnore
119
     */
120
    public function rewriteCountQuery($query)
121
    {
122
        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...
123
            return '';
124
        }
125
126
        if (preg_match('/^\s*SELECT\s+\bDISTINCT\b/is', $query) || preg_match('/\s+GROUP\s+BY\s+/is', $query)) {
127
            return '';
128
        }
129
130
        $openParenthesis = '(?:\()';
131
        $closeParenthesis = '(?:\))';
132
        $subQueryInSelect = $openParenthesis . '.*\bFROM\b.*' . $closeParenthesis;
133
        $pattern = '/(?:.*' . $subQueryInSelect . '.*)\bFROM\b\s+/Uims';
134
        if (preg_match($pattern, $query)) {
135
            return '';
136
        }
137
138
        $subQueryWithLimitOrder = $openParenthesis . '.*\b(LIMIT|ORDER)\b.*' . $closeParenthesis;
139
        $pattern = '/.*\bFROM\b.*(?:.*' . $subQueryWithLimitOrder . '.*).*/Uims';
140
        if (preg_match($pattern, $query)) {
141
            return '';
142
        }
143
144
        $queryCount = preg_replace('/(?:.*)\bFROM\b\s+/Uims', 'SELECT COUNT(*) FROM ', $query, 1);
145
        /** @var array<int> $split */
146
        $split = preg_split('/\s+ORDER\s+BY\s+/is', (string) $queryCount);
147
        [$queryCount] = $split;
148
        /** @var array<int> $split2 */
149
        $split2 = preg_split('/\bLIMIT\b/is', (string) $queryCount);
150
        [$queryCount2] = $split2;
151
152
        return trim((string) $queryCount2);
153
    }
154
}
155