1
|
|
|
<?php |
2
|
|
|
namespace Kir\MySQL\Builder\Traits; |
3
|
|
|
|
4
|
|
|
use Kir\MySQL\Databases\MySQL; |
5
|
|
|
use Kir\MySQL\Tools\VirtualTable; |
6
|
|
|
|
7
|
|
|
trait TableNameBuilder { |
8
|
|
|
use AbstractAliasReplacer; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @param string $alias |
12
|
|
|
* @param string|array|object $name |
13
|
|
|
* @return string |
14
|
|
|
*/ |
15
|
|
|
protected function buildTableName($alias, $name) { |
16
|
|
|
if(is_object($name) && !($name instanceof VirtualTable) && method_exists($name, '__toString')) { |
17
|
|
|
$name = (string) $name; |
18
|
|
|
$lines = explode("\n", $name); |
19
|
|
|
foreach($lines as &$line) { |
20
|
|
|
$line = "\t{$line}"; |
21
|
|
|
} |
22
|
|
|
$name = join("\n", $lines); |
23
|
|
|
$name = '(' . trim(rtrim(trim($name), ';')) . ')'; |
24
|
|
|
} |
25
|
|
|
if(is_array($name)) { |
26
|
|
|
$parts = []; |
27
|
|
|
foreach($name as $index => $bucket) { |
28
|
|
|
if(ctype_digit((string) $index) && is_scalar($bucket)) { |
29
|
|
|
$parts[] = "SELECT {$this->db()->quote($bucket)} AS {$this->db()->quoteField('value')}"; |
30
|
|
|
} else { |
31
|
|
|
$values = []; |
32
|
|
|
foreach($bucket as $field => $value) { |
33
|
|
|
$values[] = sprintf('%s AS %s', $this->db()->quote($value), $this->db()->quoteField($field)); |
34
|
|
|
} |
35
|
|
|
$parts[] = sprintf("SELECT %s", join(', ', $values)); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
$name = '(' . join("\n\tUNION\n\t", $parts) . ')'; |
39
|
|
|
} |
40
|
|
|
if($this->db()->getVirtualTables()->has($name)) { |
41
|
|
|
$select = (string) $this->db()->getVirtualTables()->get($name); |
42
|
|
|
$name = sprintf('(%s)', join("\n\t", explode("\n", trim($select)))); |
43
|
|
|
} |
44
|
|
|
$name = $this->aliasReplacer()->replace($name); |
|
|
|
|
45
|
|
|
if($alias !== null) { |
|
|
|
|
46
|
|
|
return sprintf("%s %s", $name, $alias); |
47
|
|
|
} |
48
|
|
|
return $name; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @return MySQL |
53
|
|
|
*/ |
54
|
|
|
abstract protected function db(); |
55
|
|
|
} |
56
|
|
|
|