Passed
Pull Request — master (#20362)
by Wilmer
05:37
created

JsonExpressionBuilder::build()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 3
nop 2
dl 0
loc 15
ccs 0
cts 9
cp 0
crap 12
rs 9.9666
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db\pgsql;
9
10
use yii\db\ArrayExpression;
11
use yii\db\ExpressionBuilderInterface;
12
use yii\db\ExpressionBuilderTrait;
13
use yii\db\ExpressionInterface;
14
use yii\db\JsonExpression;
15
use yii\db\Query;
16
use yii\helpers\Json;
17
18
/**
19
 * Class JsonExpressionBuilder builds [[JsonExpression]] for PostgreSQL DBMS.
20
 *
21
 * @author Dmytro Naumenko <[email protected]>
22
 * @since 2.0.14
23
 */
24
class JsonExpressionBuilder implements ExpressionBuilderInterface
25
{
26
    use ExpressionBuilderTrait;
27
28
29
    /**
30
     * {@inheritdoc}
31
     * @param JsonExpression|ExpressionInterface $expression the expression to be built
32
     */
33
    public function build(ExpressionInterface $expression, array &$params = [])
34
    {
35
        $value = $expression->getValue();
0 ignored issues
show
Bug introduced by
The method getValue() does not exist on yii\db\ExpressionInterface. It seems like you code against a sub-type of yii\db\ExpressionInterface such as yii\db\JsonExpression or yii\db\Query or yii\db\ArrayExpression or yii\db\PdoValue or yii\db\Expression or yii\db\conditions\BetweenColumnsCondition or yii\db\conditions\SimpleCondition. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

35
        /** @scrutinizer ignore-call */ 
36
        $value = $expression->getValue();
Loading history...
36
37
        if ($value instanceof Query) {
38
            list ($sql, $params) = $this->queryBuilder->build($value, $params);
39
            return "($sql)" . $this->getTypecast($expression);
40
        }
41
        if ($value instanceof ArrayExpression) {
42
            $placeholder = 'array_to_json(' . $this->queryBuilder->buildExpression($value, $params) . ')';
43
        } else {
44
            $placeholder = $this->queryBuilder->bindParam(Json::encode($value), $params);
45
        }
46
47
        return $placeholder . $this->getTypecast($expression);
48
    }
49
50
    /**
51
     * @param JsonExpression $expression
52
     * @return string the typecast expression based on [[type]].
53
     */
54
    protected function getTypecast(JsonExpression $expression)
55
    {
56
        if ($expression->getType() === null) {
57
            return '';
58
        }
59
60
        return '::' . $expression->getType();
61
    }
62
}
63