-
Notifications
You must be signed in to change notification settings - Fork 103
/
Conditional.php
117 lines (98 loc) · 3.19 KB
/
Conditional.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
/**
* @license MIT
* @license http://opensource.org/licenses/MIT
*/
namespace FaaPz\PDO\Clause;
use FaaPz\PDO\QueryInterface;
class Conditional implements ConditionalInterface
{
/** @var string $column */
protected $column;
/** @var string $operator */
protected $operator;
/** @var float|int|string|array<float|int|string>|MethodInterface|RawInterface $value */
protected $value;
/**
* @param string $column
* @param string $operator
* @param float|int|string|array<float|int|string>|MethodInterface|RawInterface $value
*/
public function __construct(string $column, string $operator, $value)
{
$this->column = $column;
$this->operator = strtoupper(trim($operator));
$this->value = $value;
}
/**
* @return array<mixed>
*/
public function getValues(): array
{
$values = $this->value;
if (!is_array($values)) {
$values = [$values];
}
$count = count($values);
for ($i = 0; $i < $count; $i++) {
if ($values[$i] instanceof QueryInterface) {
$value = $values[$i]->getValues();
array_splice($values, $i, 1, $value);
$i += count($value);
}
}
return $values;
}
/**
* @param mixed $value
*
* @return string
*/
protected function renderPlaceholder($value): string
{
$placeholder = '?';
if ($value instanceof QueryInterface) {
$placeholder = "{$value}";
}
return $placeholder;
}
/**
* @return string
*/
public function __toString(): string
{
$sql = "{$this->column} {$this->operator} ";
switch ($this->operator) {
case 'BETWEEN':
case 'NOT BETWEEN':
if (!is_array($this->value) || count($this->value) != 2) {
trigger_error(
"Conditional operator '{$this->operator}' requires an array with exactly two arguments",
E_USER_ERROR
);
}
$sql .= "({$this->renderPlaceholder($this->value[0])} AND {$this->renderPlaceholder($this->value[1])})";
break;
case 'IN':
case 'NOT IN':
if (!is_array($this->value) || count($this->value) < 1) {
trigger_error(
"Conditional operator '{$this->operator}' requires an array with at least one argument",
E_USER_ERROR
);
}
$placeholders = '';
foreach ($this->value as $value) {
if (!empty($placeholders)) {
$placeholders .= ', ';
}
$placeholders .= $this->renderPlaceholder($value);
}
$sql .= "({$placeholders})";
break;
default:
$sql .= $this->renderPlaceholder($this->value);
}
return $sql;
}
}