ExtendedPdoAdapter::getLimitClause()   B
last analyzed

Complexity

Conditions 7
Paths 8

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 10
cts 10
cp 1
rs 8.8333
c 0
b 0
f 0
cc 7
nc 8
nop 2
crap 7
1
<?php
2
/**
3
 * This file is part of the Ray.AuraSqlModule package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace Ray\AuraSqlModule\Pagerfanta;
8
9
use Aura\Sql\ExtendedPdo;
10
use Aura\Sql\ExtendedPdoInterface;
11
use Pagerfanta\Adapter\AdapterInterface;
12
13
class ExtendedPdoAdapter implements AdapterInterface
14
{
15
    /**
16
     * @var ExtendedPdoInterface
17
     */
18
    private $pdo;
19
20
    /**
21
     * @var string
22
     */
23
    private $sql;
24
25
    /**
26
     * @var array
27
     */
28
    private $params;
29
30 14
    public function __construct(ExtendedPdoInterface $pdo, string $sql, array $params)
31
    {
32 14
        $this->pdo = $pdo;
33 14
        $this->sql = $sql;
34 14
        $this->params = $params;
35 14
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40 9
    public function getNbResults()
41
    {
42
        // be smart and try to guess the total number of records
43 9
        $countQuery = $this->rewriteCountQuery($this->sql);
44 9
        if (! $countQuery) {
45
            // GROUP BY => fetch the whole result set and count the rows returned
46 1
            $result = $this->pdo->query($this->sql)->fetchAll();
47 1
            $count = \count($result);
48
49 1
            return $count;
50
        }
51 8
        if ($this->params) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->params of type array 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...
52
            /** @var ExtendedPdo $pdo */
53 2
            $pdo = $this->pdo;
54 2
            $sth = $pdo->prepareWithValues($this->sql, $this->params);
55 2
            $sth->execute();
56 2
            $count = $sth->fetchAll();
57
58 2
            return \count($count);
59
        }
60 6
        $count = $this->pdo->query($countQuery)->fetchColumn();
61
62 6
        return (int) $count;
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 6
    public function getSlice($offset, $length)
69
    {
70 6
        $sql = $this->sql . $this->getLimitClause($offset, $length);
71 6
        $result = $this->pdo->perform($sql, $this->params)->fetchAll(\PDO::FETCH_ASSOC);
72
73 6
        return $result;
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79 9
    public function getLimitClause($offset, $length)
80
    {
81 9
        $hasLimit = $offset || $length;
82 9
        if ($offset && $length) {
83 5
            $clause = PHP_EOL . "LIMIT {$length}";
84 5
            if ($offset) {
85 5
                $clause .= " OFFSET {$offset}";
86
            }
87
88 5
            return $clause;
89
        }
90
91 4
        if ($hasLimit && $length) {
92 3
            return PHP_EOL . "LIMIT {$length}";
93
        }
94
95 1
        return '';
96
    }
97
98
    /**
99
     * Return count query
100
     *
101
     * @param string $query
102
     *
103
     * @return string
104
     *
105
     * @see https://github.com/pear/Pager/blob/master/examples/Pager_Wrapper.php
106
     * Taken from pear/pager and modified.
107
     * tested at https://github.com/pear/Pager/blob/80c0e31c8b94f913cfbdeccbe83b63822f42a2f8/tests/pager_wrapper_test.php#L19
108
     * @codeCoverageIgnore
109
     */
110
    public function rewriteCountQuery($query)
111
    {
112
        if (\preg_match('/^\s*SELECT\s+\bDISTINCT\b/is', $query) || \preg_match('/\s+GROUP\s+BY\s+/is', $query)) {
113
            return '';
114
        }
115
        $openParenthesis = '(?:\()';
116
        $closeParenthesis = '(?:\))';
117
        $subQueryInSelect = $openParenthesis . '.*\bFROM\b.*' . $closeParenthesis;
118
        $pattern = '/(?:.*' . $subQueryInSelect . '.*)\bFROM\b\s+/Uims';
119
        if (\preg_match($pattern, $query)) {
120
            return '';
121
        }
122
        $subQueryWithLimitOrder = $openParenthesis . '.*\b(LIMIT|ORDER)\b.*' . $closeParenthesis;
123
        $pattern = '/.*\bFROM\b.*(?:.*' . $subQueryWithLimitOrder . '.*).*/Uims';
124
        if (\preg_match($pattern, $query)) {
125
            return '';
126
        }
127
        $queryCount = \preg_replace('/(?:.*)\bFROM\b\s+/Uims', 'SELECT COUNT(*) FROM ', $query, 1);
128
        list($queryCount) = \preg_split('/\s+ORDER\s+BY\s+/is', $queryCount);
129
        list($queryCount) = \preg_split('/\bLIMIT\b/is', $queryCount);
130
131
        return \trim($queryCount);
132
    }
133
}
134