|
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
|
|
|
//Needs to be broken up into better methods |
|
24
|
|
|
public function createSql($fields, $mode = \Maphper\Maphper::FIND_EXACT | \Maphper\Maphper::FIND_AND){ |
|
25
|
|
|
$args = []; |
|
26
|
|
|
$sql = []; |
|
27
|
|
|
|
|
28
|
|
|
foreach ($fields as $key => $value) { |
|
29
|
|
|
$value = $this->convertDates($value); |
|
30
|
|
|
|
|
31
|
|
|
if (is_object($value)) continue; |
|
32
|
|
|
if (is_numeric($key) && is_array($value)) { |
|
33
|
|
|
$result = $this->createSql($value, $key); |
|
34
|
|
|
} |
|
35
|
|
|
else { |
|
36
|
|
|
$result = $this->getConditional($key, $value, $mode); |
|
37
|
|
|
} |
|
38
|
|
|
$sql = array_merge($sql, $result['sql']); |
|
39
|
|
|
$args = array_merge($args, $result['args']); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
if (\Maphper\Maphper::FIND_OR & $mode) $query = implode(' OR ', $sql); |
|
43
|
|
|
else $query = implode(' AND ', $sql); |
|
44
|
|
|
if (!empty($query)) $query = '(' . $query . ')'; |
|
45
|
|
|
return ['args' => $args, 'sql' => $query]; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
private function getConditional($key, $value, $mode) { |
|
49
|
|
|
foreach ($this->conditionals as $conditional) { |
|
50
|
|
|
if ($conditional->matches($key, $value, $mode)) |
|
51
|
|
|
return $conditional->getSql($key, $value, $mode); |
|
52
|
|
|
} |
|
53
|
|
|
throw new \Exception("Invalid WHERE query"); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
private function convertDates($value) { |
|
57
|
|
|
if ($value instanceof \DateTime) { |
|
58
|
|
|
if ($value->format('H:i:s') == '00:00:00') $value = $value->format('Y-m-d'); |
|
59
|
|
|
else $value = $value->format('Y-m-d H:i:s'); |
|
60
|
|
|
} |
|
61
|
|
|
return $value; |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|