Passed
Push — master ( 1f4c93...dcd4be )
by Alexander
13:16 queued 10:08
created

JsonExpressionBuilder   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 29
ccs 9
cts 9
cp 1
rs 10
c 0
b 0
f 0
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 18 2
A __construct() 0 2 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql\Builder;
6
7
use JsonException;
8
use Yiisoft\Db\Exception\Exception;
9
use Yiisoft\Db\Exception\InvalidArgumentException;
10
use Yiisoft\Db\Exception\InvalidConfigException;
11
use Yiisoft\Db\Exception\NotSupportedException;
12
use Yiisoft\Db\Expression\ExpressionBuilderInterface;
13
use Yiisoft\Db\Expression\ExpressionInterface;
14
use Yiisoft\Db\Expression\JsonExpression;
15
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
16
use Yiisoft\Db\Query\QueryInterface;
17
use Yiisoft\Json\Json;
18
19
use function count;
20
21
/**
22
 * The class JsonExpressionBuilder builds {@see JsonExpression} for Mysql database.
23
 */
24
final class JsonExpressionBuilder implements ExpressionBuilderInterface
25
{
26
    public const PARAM_PREFIX = ':qp';
27
28 11
    public function __construct(private QueryBuilderInterface $queryBuilder)
29
    {
30
    }
31
32
    /**
33
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
34
     */
35 11
    public function build(ExpressionInterface $expression, array &$params = []): string
36
    {
37
        /**
38
         * @var JsonExpression $expression
39
         * @var mixed|QueryInterface $value
40
         */
41 11
        $value = $expression->getValue();
42
43 11
        if ($value instanceof QueryInterface) {
44 2
            [$sql, $params] = $this->queryBuilder->build($value, $params);
45
46 2
            return "($sql)";
47
        }
48
49 9
        $placeholder = self::PARAM_PREFIX . count($params);
50 9
        $params[$placeholder] = Json::encode($value);
51
52 9
        return "CAST($placeholder AS JSON)";
53
    }
54
}
55