Completed
Push — master ( 7fd4a2...4773f0 )
by Konstantin
14:28 queued 09:30
created

Util::prepareQuery()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 47
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 5.0073

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 47
ccs 28
cts 30
cp 0.9333
rs 8.5125
cc 5
eloc 27
nc 7
nop 3
crap 5.0073
1
<?php
2
3
namespace Brouzie\Sphinxy;
4
5
use Brouzie\Sphinxy\Exception\ExtraParametersException;
6
use Brouzie\Sphinxy\Exception\ParameterNotFoundException;
7
8
class Util
9
{
10
    /**
11
     * This code ported from https://github.com/auraphp/Aura.Sql/blob/master/src/Aura/Sql/Connection/AbstractConnection.php.
12
     *
13
     * @param $query
14
     * @param $params
15
     *
16
     * @license http://opensource.org/licenses/bsd-license.php BSD
17
     *
18
     * @return string
19
     */
20 31
    public static function prepareQuery($query, $params, Escaper $escaper)
21
    {
22
        // find all text parts not inside quotes or backslashed-quotes
23 31
        $apos = "'";
24 31
        $quot = '"';
25 11
        $parts = preg_split(
26 31
            "/(($apos+|$quot+|\\$apos+|\\$quot+).*?)\\2/m",
27
            $query,
28 31
            -1,
29 31
            PREG_SPLIT_DELIM_CAPTURE
30
        );
31
32 31
        $usedParams = array();
33
        // loop through the non-quoted parts (0, 3, 6, 9, etc.)
34 11
        for ($i = 0, $k = count($parts); $i <= $k; $i += 3) {
35
            // get the part as a reference so it can be modified in place
36 29
            $part = &$parts[$i];
37
38
            // find all :placeholder matches in the part
39 11
            preg_match_all(
40 29
                "/\W:([a-zA-Z_][a-zA-Z0-9_]*)/m",
41 29
                $part.PHP_EOL,
42
                $matches
43
            );
44
45
            // for each of the :placeholder matches ...
46 29
            foreach ($matches[1] as $key) {
47 8
                if (!array_key_exists($key, $params)) {
48 3
                    throw new ParameterNotFoundException(sprintf('The parameter "%s" not found.', $key));
49
                }
50
51 14
                $find = "/(^|\W)(:$key)(\W|$)/m";
52 6
                $repl = '${1}'.addcslashes($escaper->quote($params[$key]), '\\').'${3}';
53 6
                $part = preg_replace($find, $repl, $part);
54 14
                $usedParams[$key] = true;
55 8
            }
56 6
        }
57
58 8
        if (count($params) > count($usedParams)) {
59 3
            throw new ExtraParametersException(sprintf(
60 9
                'Extra parameters found: %s.',
61 3
                implode(', ', array_keys(array_diff_key($params, $usedParams)))
62
            ));
63
        }
64
65 5
        return implode('', $parts);
66 14
    }
67
}
68