Passed
Push — master ( 71d24f...562277 )
by Richard
01:37
created

WhereBuilder::createSql()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 12
nc 4
nop 2
dl 0
loc 19
rs 8.8571
c 1
b 0
f 0
1
<?php
2
namespace Maphper\Lib\Sql;
3
4
class WhereBuilder {
5
    private $conditionals = [];
6
7
    public function __construct() {
8
        $defaultConditionals = [
9
            'Maphper\Lib\Sql\Between',
10
            'Maphper\Lib\Sql\In',
11
            'Maphper\Lib\Sql\NullConditional',
12
            'Maphper\Lib\Sql\Like',
13
            'Maphper\Lib\Sql\GeneralOperator'
14
        ];
15
16
        foreach ($defaultConditionals as $conditional) $this->addConditional(new $conditional);
17
    }
18
19
    public function addConditional(WhereConditional $conditional) {
20
        $this->conditionals[] = $conditional;
21
    }
22
23
	public function createSql($fields, $mode = \Maphper\Maphper::FIND_EXACT | \Maphper\Maphper::FIND_AND) {
24
		$args = [];
25
		$sql = [];
26
27
        foreach ($fields as $key => $value) {
28
            $value = $this->convertDates($value);
29
30
            if (is_object($value)) continue;
31
			if (is_numeric($key) && is_array($value)) {
32
				$result = $this->createSql($value, $key);
33
			}
34
            else {
35
                $result = $this->getConditional($key, $value, $mode);
36
            }
37
            $sql = array_merge($sql, (array)$result['sql']);
38
            $args = array_merge($args, $result['args']);
39
        }
40
41
		return ['args' => $args, 'sql' => $this->sqlArrayToString($sql, $mode)];
42
	}
43
44
    private function sqlArrayToString($sql, $mode) {
45
        if (\Maphper\Maphper::FIND_OR & $mode) $query = implode(' OR  ', $sql);
46
		else $query = implode(' AND ', $sql);
47
		if (!empty($query)) $query = '(' . $query . ')';
48
        return $query;
49
    }
50
51
    private function getConditional($key, $value, $mode) {
52
        foreach ($this->conditionals as $conditional) {
53
            if ($conditional->matches($key, $value, $mode))
54
                return $conditional->getSql($key, $value, $mode);
55
        }
56
        throw new \Exception("Invalid WHERE query");
57
    }
58
59
    private function convertDates($value) {
60
        if ($value instanceof \DateTime) {
61
            if ($value->format('H:i:s')  == '00:00:00') $value = $value->format('Y-m-d');
62
            else $value = $value->format('Y-m-d H:i:s');
63
        }
64
        return $value;
65
    }
66
}
67