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

JsonExpressionBuilder::build()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 7
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 18
ccs 8
cts 8
cp 1
crap 2
rs 10
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