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
|
33 |
|
public static function prepareQuery($query, $params, Escaper $escaper) |
21
|
|
|
{ |
22
|
|
|
// find all text parts not inside quotes or backslashed-quotes |
23
|
33 |
|
$apos = "'"; |
24
|
33 |
|
$quot = '"'; |
25
|
33 |
|
$parts = preg_split( |
26
|
33 |
|
"/(($apos+|$quot+|\\$apos+|\\$quot+).*?)\\2/m", |
27
|
33 |
|
$query, |
28
|
33 |
|
-1, |
29
|
11 |
|
PREG_SPLIT_DELIM_CAPTURE |
30
|
22 |
|
); |
31
|
|
|
|
32
|
33 |
|
$usedParams = array(); |
33
|
|
|
// loop through the non-quoted parts (0, 3, 6, 9, etc.) |
34
|
33 |
|
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
|
33 |
|
$part = &$parts[$i]; |
37
|
|
|
|
38
|
|
|
// find all :placeholder matches in the part |
39
|
33 |
|
preg_match_all( |
40
|
33 |
|
"/\W:([a-zA-Z_][a-zA-Z0-9_]*)/m", |
41
|
33 |
|
$part.PHP_EOL, |
42
|
11 |
|
$matches |
43
|
22 |
|
); |
44
|
|
|
|
45
|
|
|
// for each of the :placeholder matches ... |
46
|
33 |
|
foreach ($matches[1] as $key) { |
47
|
24 |
|
if (!array_key_exists($key, $params)) { |
48
|
9 |
|
throw new ParameterNotFoundException(sprintf('The parameter "%s" not found.', $key)); |
49
|
|
|
} |
50
|
|
|
|
51
|
18 |
|
$find = "/(^|\W)(:$key)(\W|$)/m"; |
52
|
18 |
|
$repl = '${1}'.addcslashes($escaper->quote($params[$key]), '\\').'${3}'; |
53
|
18 |
|
$part = preg_replace($find, $repl, $part); |
54
|
18 |
|
$usedParams[$key] = true; |
55
|
18 |
|
} |
56
|
16 |
|
} |
57
|
|
|
|
58
|
24 |
|
if (count($params) > count($usedParams)) { |
59
|
9 |
|
throw new ExtraParametersException(sprintf( |
60
|
9 |
|
'Extra parameters found: %s.', |
61
|
9 |
|
implode(', ', array_keys(array_diff_key($params, $usedParams))) |
62
|
6 |
|
)); |
63
|
|
|
} |
64
|
|
|
|
65
|
15 |
|
return implode('', $parts); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|