Completed
Push — master ( 354401...52d456 )
by Ron
01:49
created

TableNameBuilder::buildTableName()   D

Complexity

Conditions 9
Paths 16

Size

Total Lines 31
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 4.909
c 0
b 0
f 0
cc 9
eloc 23
nc 16
nop 2
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 $name
13
	 * @return string
14
	 */
15
	protected function buildTableName($alias, $name) {
16
		if(is_object($name) && !($name instanceof VirtualTable)) {
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 $bucket) {
28
				$values = [];
29
				foreach($bucket as $field => $value) {
30
					$values[] = sprintf('%s AS %s', $this->db()->quote($value), $this->db()->quoteField($field));
31
				}
32
				$parts[] = sprintf("SELECT %s", join(', ', $values));
33
			}
34
			$name = '(' . join("\n\tUNION\n\t", $parts) . ')';
35
		}
36
		if($this->db()->getVirtualTables()->has($name)) {
37
			$select = (string) $this->db()->getVirtualTables()->get($name);
38
			$name = sprintf('(%s)', join("\n\t", explode("\n", trim($select))));
39
		}
40
		$name = $this->aliasReplacer()->replace($name);
41
		if($alias !== null) {
42
			return sprintf("%s %s", $name, $alias);
43
		}
44
		return $name;
45
	}
46
	
47
	/**
48
	 * @return MySQL
49
	 */
50
	abstract protected function db();
51
}
52