Passed
Pull Request — dev (#98)
by Wilmer
43:38 queued 28:30
created

JsonExpressionBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 0
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 2
ccs 0
cts 0
cp 0
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\Query\Query;
16
use Yiisoft\Db\Query\QueryBuilderInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Query\QueryBuilderInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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
    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|Query $value
40
         */
41 11
        $value = $expression->getValue();
42
43 11
        if ($value instanceof Query) {
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