1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of Phuria SQL Builder package. |
5
|
|
|
* |
6
|
|
|
* Copyright (c) 2016 Beniamin Jonatan Šimko |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Phuria\UnderQuery\QueryCompiler; |
13
|
|
|
|
14
|
|
|
use Phuria\UnderQuery\QueryBuilder\AbstractBuilder; |
15
|
|
|
use Phuria\UnderQuery\QueryBuilder\BuilderInterface; |
16
|
|
|
use Phuria\UnderQuery\Table\AbstractTable; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @author Beniamin Jonatan Šimko <[email protected]> |
20
|
|
|
*/ |
21
|
|
|
class ReferenceCompiler |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @param CompilerPayload $payload |
25
|
|
|
* |
26
|
|
|
* @return CompilerPayload |
27
|
|
|
*/ |
28
|
|
|
public function compileReference(CompilerPayload $payload) |
29
|
|
|
{ |
30
|
|
|
$builder = $payload->getBuilder(); |
31
|
|
|
$references = []; |
32
|
|
|
|
33
|
|
|
if ($builder instanceof AbstractBuilder) { |
34
|
|
|
$references = $builder->getReferences()->toArray(); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$actualSQL = $this->compile($payload->getActualSQL(), $references); |
38
|
|
|
|
39
|
|
|
return $payload->updateSQL($actualSQL); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param string $rawSQL |
44
|
|
|
* @param array $references |
45
|
|
|
* |
46
|
|
|
* @return string |
47
|
|
|
*/ |
48
|
|
|
public function compile($rawSQL, array $references) |
49
|
|
|
{ |
50
|
|
|
foreach ($references as &$value) { |
51
|
|
|
$value = $this->convertReferenceToValue($value); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return str_replace(array_keys($references), array_values($references), $rawSQL); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param $reference |
59
|
|
|
* |
60
|
|
|
* @return string |
61
|
|
|
*/ |
62
|
|
|
private function convertReferenceToValue($reference) |
63
|
|
|
{ |
64
|
|
|
if (is_string($reference)) { |
65
|
|
|
return "\"" . $reference ."\""; |
66
|
|
|
} elseif ($reference instanceof AbstractTable) { |
67
|
|
|
return $reference->getAliasOrName(); |
68
|
|
|
} elseif ($reference instanceof BuilderInterface) { |
69
|
|
|
return $reference->buildSQL(); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return $reference; |
73
|
|
|
} |
74
|
|
|
} |