1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Sirius\Sql; |
5
|
|
|
|
6
|
|
|
use PDO; |
7
|
|
|
|
8
|
|
|
class Bindings |
9
|
|
|
{ |
10
|
|
|
protected $values = []; |
11
|
|
|
|
12
|
|
|
protected $inlineCount = 0; |
13
|
|
|
|
14
|
16 |
|
public function value(string $key, $value, int $type = -1) |
15
|
|
|
{ |
16
|
16 |
|
if ($type === -1) { |
17
|
16 |
|
$type = $this->getType($value); |
18
|
|
|
} |
19
|
16 |
|
$this->values[$key] = [$value, $type]; |
20
|
16 |
|
} |
21
|
|
|
|
22
|
16 |
|
protected function getType($value) |
23
|
|
|
{ |
24
|
16 |
|
if (is_null($value)) { |
25
|
|
|
return PDO::PARAM_NULL; |
26
|
|
|
} |
27
|
|
|
|
28
|
16 |
|
if (is_bool($value)) { |
29
|
|
|
return PDO::PARAM_BOOL; |
30
|
|
|
} |
31
|
|
|
|
32
|
16 |
|
if (is_int($value)) { |
33
|
12 |
|
return PDO::PARAM_INT; |
34
|
|
|
} |
35
|
|
|
|
36
|
9 |
|
return PDO::PARAM_STR; |
37
|
|
|
} |
38
|
|
|
|
39
|
1 |
|
public function values(array $values, int $type = -1) |
40
|
|
|
{ |
41
|
1 |
|
foreach ($values as $key => $value) { |
42
|
1 |
|
$this->value($key, $value, $type); |
43
|
|
|
} |
44
|
1 |
|
} |
45
|
|
|
|
46
|
11 |
|
public function getArrayCopy(): array |
47
|
|
|
{ |
48
|
11 |
|
return $this->values; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function remove(string $key) |
52
|
|
|
{ |
53
|
|
|
unset($this->values[$key]); |
54
|
|
|
} |
55
|
|
|
|
56
|
14 |
|
public function inline($value, int $type = -1): string |
57
|
|
|
{ |
58
|
14 |
|
if ($value instanceof Select) { |
59
|
|
|
return '(' . $value->getStatement() . ')'; |
60
|
|
|
} |
61
|
|
|
|
62
|
14 |
|
if (is_array($value)) { |
63
|
3 |
|
return $this->inlineArray($value, $type); |
64
|
|
|
} |
65
|
|
|
|
66
|
14 |
|
$this->inlineCount++; |
67
|
14 |
|
$key = "__{$this->inlineCount}__"; |
68
|
14 |
|
$this->value($key, $value, $type); |
69
|
|
|
|
70
|
14 |
|
return ":{$key}"; |
71
|
|
|
} |
72
|
|
|
|
73
|
3 |
|
protected function inlineArray(array $array, int $type): string |
74
|
|
|
{ |
75
|
3 |
|
$keys = []; |
76
|
|
|
|
77
|
3 |
|
foreach ($array as $value) { |
78
|
3 |
|
$this->inlineCount++; |
79
|
3 |
|
$key = "__{$this->inlineCount}__"; |
80
|
3 |
|
$this->value($key, $value, $type); |
81
|
3 |
|
$keys[] = ":{$key}"; |
82
|
|
|
} |
83
|
|
|
|
84
|
3 |
|
return '(' . implode(', ', $keys) . ')'; |
85
|
|
|
} |
86
|
|
|
|
87
|
4 |
|
public function sprintf(string $format, ...$values): string |
88
|
|
|
{ |
89
|
4 |
|
$tokens = []; |
90
|
|
|
|
91
|
4 |
|
foreach ($values as $value) { |
92
|
4 |
|
$tokens[] = $this->inline($value); |
93
|
|
|
} |
94
|
|
|
|
95
|
4 |
|
return sprintf($format, ...$tokens); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|