1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Db\QueryBuilder\Condition\Builder; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Db\Exception\Exception; |
8
|
|
|
use Yiisoft\Db\Exception\InvalidArgumentException; |
9
|
|
|
use Yiisoft\Db\Exception\InvalidConfigException; |
10
|
|
|
use Yiisoft\Db\Exception\NotSupportedException; |
11
|
|
|
use Yiisoft\Db\Expression\ExpressionBuilderInterface; |
12
|
|
|
use Yiisoft\Db\Expression\ExpressionInterface; |
13
|
|
|
use Yiisoft\Db\QueryBuilder\Condition\InCondition; |
14
|
|
|
use Yiisoft\Db\QueryBuilder\Condition\Interface\HashConditionInterface; |
15
|
|
|
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface; |
16
|
|
|
use Yiisoft\Db\Query\QueryInterface; |
17
|
|
|
|
18
|
|
|
use function count; |
19
|
|
|
use function implode; |
20
|
|
|
use function is_iterable; |
21
|
|
|
use function str_contains; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Build an object of {@see HashCondition} into SQL expressions. |
25
|
|
|
*/ |
26
|
|
|
class HashConditionBuilder implements ExpressionBuilderInterface |
27
|
|
|
{ |
28
|
|
|
public function __construct(private QueryBuilderInterface $queryBuilder) |
29
|
|
|
{ |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Build SQL for {@see HashCondition}. |
34
|
|
|
* |
35
|
|
|
* @throws Exception |
36
|
|
|
* @throws InvalidArgumentException |
37
|
|
|
* @throws InvalidConfigException |
38
|
|
|
* @throws NotSupportedException |
39
|
|
|
*/ |
40
|
|
|
public function build(HashConditionInterface $expression, array &$params = []): string |
41
|
|
|
{ |
42
|
|
|
$hash = $expression->getHash() ?? []; |
43
|
|
|
$parts = []; |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @psalm-var array<string, array|mixed> $hash |
47
|
|
|
* @psalm-var array|mixed $value |
48
|
|
|
*/ |
49
|
|
|
foreach ($hash as $column => $value) { |
50
|
|
|
if (is_iterable($value) || $value instanceof QueryInterface) { |
51
|
|
|
/** IN condition */ |
52
|
|
|
$parts[] = $this->queryBuilder->buildCondition(new InCondition($column, 'IN', $value), $params); |
53
|
|
|
} else { |
54
|
|
|
if (!str_contains($column, '(')) { |
55
|
|
|
$column = $this->queryBuilder->quoter()->quoteColumnName($column); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
if ($value === null) { |
59
|
|
|
$parts[] = "$column IS NULL"; |
60
|
|
|
} elseif ($value instanceof ExpressionInterface) { |
61
|
|
|
$parts[] = "$column=" . $this->queryBuilder->buildExpression($value, $params); |
62
|
|
|
} else { |
63
|
|
|
$phName = $this->queryBuilder->bindParam($value, $params); |
64
|
|
|
$parts[] = "$column=$phName"; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return (count($parts) === 1) ? $parts[0] : ('(' . implode(') AND (', $parts) . ')'); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|