|
1
|
|
|
<?php |
|
2
|
|
|
namespace Kir\MySQL\Builder\Internal; |
|
3
|
|
|
|
|
4
|
|
|
use Kir\MySQL\Builder\Expr\OptionalExpression; |
|
5
|
|
|
use Kir\MySQL\Database; |
|
6
|
|
|
use Kir\MySQL\Builder; |
|
7
|
|
|
|
|
8
|
|
|
final class ConditionBuilder { |
|
9
|
|
|
/** |
|
10
|
|
|
* @param Database $db |
|
11
|
|
|
* @param string $query |
|
12
|
|
|
* @param array<int, array{string|array<string, mixed>|object|OptionalExpression, array<int, null|string|array<int, null|scalar>|Builder\DBExpr|Builder\Select>}> $conditions |
|
|
|
|
|
|
13
|
|
|
* @param string $token |
|
14
|
|
|
* @return string |
|
15
|
|
|
*/ |
|
16
|
|
|
public static function build(Database $db, string $query, array $conditions, string $token): string { |
|
17
|
|
|
if(!count($conditions)) { |
|
18
|
|
|
return $query; |
|
19
|
|
|
} |
|
20
|
|
|
$query .= "{$token}\n"; |
|
21
|
|
|
$arr = []; |
|
22
|
|
|
foreach($conditions as [$expression, $arguments]) { |
|
23
|
|
|
if(is_array($expression)) { |
|
24
|
|
|
foreach($expression as $key => $value) { |
|
25
|
|
|
$key = self::formatKey($key); |
|
26
|
|
|
if($value === null) { |
|
27
|
|
|
$arr = self::buildCondition($arr, "ISNULL({$key})", [$value], $db); |
|
28
|
|
|
} else { |
|
29
|
|
|
$arr = self::buildCondition($arr, "{$key}=?", [$value], $db); |
|
30
|
|
|
} |
|
31
|
|
|
} |
|
32
|
|
|
} else { |
|
33
|
|
|
$arr = self::buildCondition($arr, (string) $expression, $arguments, $db); |
|
34
|
|
|
} |
|
35
|
|
|
} |
|
36
|
|
|
$query .= implode("\n\tAND\n", $arr); |
|
37
|
|
|
return "{$query}\n"; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* @param array<int, string> $conditions |
|
42
|
|
|
* @param string $expression |
|
43
|
|
|
* @param array<int, null|string|array<int, null|scalar>|Builder\DBExpr|Builder\Select> $arguments |
|
44
|
|
|
* @param Database $db |
|
45
|
|
|
* @return array<int, string> |
|
46
|
|
|
*/ |
|
47
|
|
|
private static function buildCondition(array $conditions, string $expression, array $arguments, Database $db): array { |
|
48
|
|
|
$expr = $db->quoteExpression($expression, $arguments); |
|
49
|
|
|
$conditions[] = "\t({$expr})"; |
|
50
|
|
|
return $conditions; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* @param string $key |
|
55
|
|
|
* @return string |
|
56
|
|
|
*/ |
|
57
|
|
|
private static function formatKey(string $key): string { |
|
58
|
|
|
if(strpos($key, '`') !== false || strpos($key, '(') !== false) { |
|
59
|
|
|
return $key; |
|
60
|
|
|
} |
|
61
|
|
|
$keyParts = explode('.', $key); |
|
62
|
|
|
$fn = static function (string $part) { |
|
63
|
|
|
return "`{$part}`"; |
|
64
|
|
|
}; |
|
65
|
|
|
$enclosedKeyParts = array_map($fn, $keyParts); |
|
66
|
|
|
return implode('.', $enclosedKeyParts); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|