Passed
Push — master ( 562277...03179d )
by Richard
01:52
created

WhereBuilder::getResult()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 2
nc 2
nop 3
dl 0
loc 3
rs 10
c 0
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
			$result = $this->getResult($key, $value, $mode);
32
            $sql = array_merge($sql, (array)$result['sql']);
33
            $args = array_merge($args, $result['args']);
34
        }
35
36
		return ['args' => $args, 'sql' => $this->sqlArrayToString($sql, $mode)];
37
	}
38
39
    /*
40
     * Either get sql from a conditional or call createSql again because the mode needs to be changed
41
     */
42
    private function getResult($key, $value, $mode) {
43
        if (is_numeric($key) && is_array($value)) return $this->createSql($value, $key);
44
        return $this->getConditional($key, $value, $mode);
45
    }
46
47
    private function sqlArrayToString($sql, $mode) {
48
        if (\Maphper\Maphper::FIND_OR & $mode) $query = implode(' OR  ', $sql);
49
		else $query = implode(' AND ', $sql);
50
		if (!empty($query)) $query = '(' . $query . ')';
51
        return $query;
52
    }
53
54
    private function getConditional($key, $value, $mode) {
55
        foreach ($this->conditionals as $conditional) {
56
            if ($conditional->matches($key, $value, $mode))
57
                return $conditional->getSql($key, $value, $mode);
58
        }
59
        throw new \Exception("Invalid WHERE query");
60
    }
61
62
    private function convertDates($value) {
63
        if ($value instanceof \DateTime) {
64
            if ($value->format('H:i:s')  == '00:00:00') $value = $value->format('Y-m-d');
65
            else $value = $value->format('Y-m-d H:i:s');
66
        }
67
        return $value;
68
    }
69
}
70