1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bdf\Prime\Connection; |
4
|
|
|
|
5
|
|
|
use Bdf\Prime\Exception\PrimeException; |
6
|
|
|
use Bdf\Prime\Query\Contract\Compilable; |
7
|
|
|
use Doctrine\DBAL\Exception as DoctrineDBALException; |
8
|
|
|
use Doctrine\DBAL\ParameterType; |
9
|
|
|
use Doctrine\DBAL\Statement; |
10
|
|
|
|
11
|
|
|
use function is_bool; |
12
|
|
|
use function is_int; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Utility class for binding values to a statement |
16
|
|
|
*/ |
17
|
|
|
final class Binder |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Bind values to a statement |
21
|
|
|
* The parameter type is guessed from the value instead of using STRING |
22
|
|
|
* |
23
|
|
|
* @param Statement $statement Statement to bind |
24
|
|
|
* @param Compilable $query Query which contains the bindings |
25
|
|
|
* |
26
|
|
|
* @return Statement Same as the first parameter |
27
|
|
|
* |
28
|
|
|
* @throws DoctrineDBALException |
29
|
|
|
* @throws PrimeException |
30
|
|
|
*/ |
31
|
717 |
|
public static function bindValues(Statement $statement, Compilable $query): Statement |
32
|
|
|
{ |
33
|
717 |
|
$bindings = $query->getBindings(); |
34
|
717 |
|
$bindIndex = 1; |
35
|
|
|
|
36
|
717 |
|
foreach ($bindings as $key => $value) { |
37
|
|
|
switch (true) { |
38
|
699 |
|
case is_int($value): |
39
|
321 |
|
$type = ParameterType::INTEGER; |
40
|
321 |
|
break; |
41
|
|
|
|
42
|
683 |
|
case is_bool($value): |
43
|
|
|
$type = ParameterType::BOOLEAN; |
44
|
|
|
break; |
45
|
|
|
|
46
|
683 |
|
case $value === null: |
47
|
593 |
|
$type = ParameterType::NULL; |
48
|
593 |
|
break; |
49
|
|
|
|
50
|
|
|
default: |
51
|
679 |
|
$type = ParameterType::STRING; |
52
|
|
|
} |
53
|
|
|
|
54
|
699 |
|
$statement->bindValue( |
55
|
699 |
|
is_int($key) ? $bindIndex++ : $key, |
56
|
699 |
|
$value, |
57
|
699 |
|
$type |
58
|
699 |
|
); |
59
|
|
|
} |
60
|
|
|
|
61
|
717 |
|
return $statement; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Extract the parameter types from the values |
66
|
|
|
* |
67
|
|
|
* Keep original keys. |
68
|
|
|
* Follows the same rules as bindValues() |
69
|
|
|
* |
70
|
|
|
* @param mixed[] $bindings |
71
|
|
|
* @return array<ParameterType::*> |
|
|
|
|
72
|
|
|
*/ |
73
|
1119 |
|
public static function types(array $bindings): array |
74
|
|
|
{ |
75
|
1119 |
|
$types = []; |
76
|
|
|
|
77
|
1119 |
|
foreach ($bindings as $key => $value) { |
78
|
|
|
switch (true) { |
79
|
746 |
|
case is_int($value): |
80
|
638 |
|
$types[$key] = ParameterType::INTEGER; |
81
|
638 |
|
break; |
82
|
|
|
|
83
|
501 |
|
case is_bool($value): |
84
|
1 |
|
$types[$key] = ParameterType::BOOLEAN; |
85
|
1 |
|
break; |
86
|
|
|
|
87
|
501 |
|
case $value === null: |
88
|
3 |
|
$types[$key] = ParameterType::NULL; |
89
|
3 |
|
break; |
90
|
|
|
|
91
|
|
|
default: |
92
|
501 |
|
$types[$key] = ParameterType::STRING; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|
96
|
1119 |
|
return $types; |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|