1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Plasma Core component |
4
|
|
|
* Copyright 2018 PlasmaPHP, All Rights Reserved |
5
|
|
|
* |
6
|
|
|
* Website: https://github.com/PlasmaPHP |
7
|
|
|
* License: https://github.com/PlasmaPHP/core/blob/master/LICENSE |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Plasma; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Common utilities for components. |
14
|
|
|
*/ |
15
|
|
|
class Utility { |
16
|
|
|
/** |
17
|
|
|
* Parses a query containing parameters into an array, and can replace them with a predefined replacement (can be a callable). |
18
|
|
|
* The callable is used to return numbered parameters (such as used in PostgreSQL), or any other kind of parameters supported by the DBMS. |
19
|
|
|
* @param string $query |
20
|
|
|
* @param string|callable|null $replaceParams If `null` is passed, it will not replace the parameters. |
21
|
|
|
* @param string $regex |
22
|
|
|
* @return array `[ 'query' => string, 'parameters' => array ]` The `parameters` array is an numeric array (= position, starting at 1), which map to the original parameter. |
23
|
|
|
*/ |
24
|
6 |
|
static function parseParameters(string $query, $replaceParams = null, string $regex = '/(:[a-z]+)|\?|\$\d+/i'): array { |
25
|
6 |
|
$params = array(); |
26
|
6 |
|
$position = 1; |
27
|
|
|
|
28
|
|
|
$query = \preg_replace_callback($regex, function (array $match) use ($replaceParams, &$params, &$position) { |
29
|
6 |
|
$params[($position++)] = $match[0]; |
30
|
|
|
|
31
|
6 |
|
if($replaceParams !== null) { |
32
|
5 |
|
return (\is_callable($replaceParams) ? $replaceParams() : $replaceParams); |
33
|
|
|
} |
34
|
|
|
|
35
|
1 |
|
return $match[0]; |
36
|
6 |
|
}, $query); |
37
|
|
|
|
38
|
6 |
|
return array('query' => $query, 'parameters' => $params); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Replaces the user parameters keys with the correct parameters for the DBMS. |
43
|
|
|
* @param array $paramsInfo The parameters array from `parseParameters`. |
44
|
|
|
* @param array $params The parameters of the user. |
45
|
|
|
* @return array |
46
|
|
|
* @throws \Plasma\Exception |
47
|
|
|
*/ |
48
|
3 |
|
static function replaceParameters(array $paramsInfo, array $params): array { |
49
|
3 |
|
if(\count($params) !== \count($paramsInfo)) { |
50
|
2 |
|
throw new \Plasma\Exception('Insufficient amount of parameters passed, expected '.\count($paramsInfo).', got '.\count($params)); |
51
|
|
|
} |
52
|
|
|
|
53
|
1 |
|
$realParams = array(); |
54
|
1 |
|
$pos = (\array_key_exists(0, $params) ? 0 : 1); |
55
|
|
|
|
56
|
1 |
|
foreach($paramsInfo as $param) { |
57
|
1 |
|
$key = ($param[0] === ':' ? $param : ($pos++)); |
58
|
|
|
|
59
|
1 |
|
if(!\array_key_exists($key, $params)) { |
60
|
|
|
throw new \Plasma\Exception('Missing parameter with key "'.$key.'"'); |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
$realParams[] = $params[$key]; |
64
|
|
|
} |
65
|
|
|
|
66
|
1 |
|
return $realParams; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|