Passed
Push — master ( c65027...a39d50 )
by Wilmer
18:53 queued 16:02
created

HashConditionBuilder::build()   B

Complexity

Conditions 8
Paths 16

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 29
rs 8.4444
c 0
b 0
f 0
cc 8
nc 16
nop 2
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 str_contains;
21
22
/**
23
 * Class HashConditionBuilder builds objects of {@see HashCondition}.
24
 */
25
class HashConditionBuilder implements ExpressionBuilderInterface
26
{
27
    public function __construct(private QueryBuilderInterface $queryBuilder)
28
    {
29
    }
30
31
    /**
32
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
33
     *
34
     * @psalm-suppress MixedAssignment
35
     */
36
    public function build(HashConditionInterface $expression, array &$params = []): string
37
    {
38
        $hash = $expression->getHash() ?? [];
39
        $parts = [];
40
41
        /**
42
         * @psalm-var array<string, array|mixed> $hash
43
         */
44
        foreach ($hash as $column => $value) {
45
            if (is_iterable($value) || $value instanceof QueryInterface) {
46
                /** IN condition */
47
                $parts[] = $this->queryBuilder->buildCondition(new InCondition($column, 'IN', $value), $params);
48
            } else {
49
                if (!str_contains($column, '(')) {
50
                    $column = $this->queryBuilder->quoter()->quoteColumnName($column);
51
                }
52
53
                if ($value === null) {
54
                    $parts[] = "$column IS NULL";
55
                } elseif ($value instanceof ExpressionInterface) {
56
                    $parts[] = "$column=" . $this->queryBuilder->buildExpression($value, $params);
57
                } else {
58
                    $phName = $this->queryBuilder->bindParam($value, $params);
59
                    $parts[] = "$column=$phName";
60
                }
61
            }
62
        }
63
64
        return (count($parts) === 1) ? $parts[0] : ('(' . implode(') AND (', $parts) . ')');
65
    }
66
}
67