-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompiler.php
More file actions
81 lines (68 loc) · 1.57 KB
/
Compiler.php
File metadata and controls
81 lines (68 loc) · 1.57 KB
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
<?php
namespace Silver\Database;
use Silver\Database\Query;
trait Compiler
{
// Current queries stack
private static $qstack = [];
// Should be abstract, but php says: (E_STRICT)
// Static function Silver\Database\Compiler::compile() should not be abstract
protected static function compile(object $q) : array
{
throw new \Exception("This should be abstract method. Do not call it directly.");
}
public static function current(): ?object
{
if (self::$qstack) {
return self::$qstack[0];
} else {
return null;
}
}
private static function parentQuery(): ?object
{
if (count(self::$qstack) >= 2) {
return self::$qstack[1];
}
return null;
}
public function toSql(): array
{
try {
array_unshift(self::$qstack, $this);
$class = get_called_class();
$dialect = ucfirst(Db::driverName());
$pos = strrpos($class, '\\') ?: 0;
$new = substr_replace($class, '\\' . $dialect, $pos, 0);
// Remove current bindings
// (Query can be reused)
if ($this instanceof Query) {
$this->clearBindings();
}
$sql = class_exists($new)
? $new::compile($this)
: $class::compile($this);
// Add bindings to parent query
if ($this instanceof Query) {
if ($p = self::parentQuery()) {
if ($b = $this->getBindings()) {
$p->bind($b);
}
}
}
return $sql;
} finally {
array_shift(self::$qstack);
}
}
public function __toString(): string
{
try {
$sqls = $this->toSql();
return implode(";\n", $sqls);
} catch (\Exception $e) {
echo "ERROR __toString(): " . $e->getMessage() . "\n";
exit;
}
}
}