-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathCaseExpression.php
98 lines (81 loc) · 2.24 KB
/
CaseExpression.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
<?php
declare(strict_types=1);
namespace PhpMyAdmin\SqlParser\Components;
use PhpMyAdmin\SqlParser\Component;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Parsers\Conditions;
use function count;
/**
* Parses a reference to a CASE expression.
*/
final class CaseExpression implements Component
{
/**
* The value to be compared.
*/
public Expression|null $value = null;
/**
* The conditions in WHEN clauses.
*
* @var Condition[][]
*/
public array $conditions = [];
/**
* The results matching with the WHEN clauses.
*
* @var Expression[]
*/
public array $results = [];
/**
* The values to be compared against.
*
* @var Expression[]
*/
public array $compareValues = [];
/**
* The result in ELSE section of expr.
*/
public Expression|null $elseResult = null;
/**
* The alias of this CASE statement.
*/
public string|null $alias = null;
/**
* The sub-expression.
*/
public string $expr = '';
public function build(): string
{
$ret = 'CASE ';
if (isset($this->value)) {
// Syntax type 0
$ret .= $this->value . ' ';
$valuesCount = count($this->compareValues);
$resultsCount = count($this->results);
for ($i = 0; $i < $valuesCount && $i < $resultsCount; ++$i) {
$ret .= 'WHEN ' . $this->compareValues[$i] . ' ';
$ret .= 'THEN ' . $this->results[$i] . ' ';
}
} else {
// Syntax type 1
$valuesCount = count($this->conditions);
$resultsCount = count($this->results);
for ($i = 0; $i < $valuesCount && $i < $resultsCount; ++$i) {
$ret .= 'WHEN ' . Conditions::buildAll($this->conditions[$i]) . ' ';
$ret .= 'THEN ' . $this->results[$i] . ' ';
}
}
if (isset($this->elseResult)) {
$ret .= 'ELSE ' . $this->elseResult . ' ';
}
$ret .= 'END';
if ($this->alias) {
$ret .= ' AS ' . Context::escape($this->alias);
}
return $ret;
}
public function __toString(): string
{
return $this->build();
}
}