Passed
Pull Request — master (#19)
by Wilmer
12:28
created

JsonExpressionBuilder::getTypecast()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql\Expression;
6
7
use Yiisoft\Db\Exception\InvalidArgumentException;
8
use Yiisoft\Db\Expression\ArrayExpression;
9
use Yiisoft\Db\Expression\ExpressionBuilderInterface;
10
use Yiisoft\Db\Expression\ExpressionBuilderTrait;
11
use Yiisoft\Db\Expression\ExpressionInterface;
12
use Yiisoft\Db\Expression\JsonExpression;
13
use Yiisoft\Db\Query\Query;
14
use Yiisoft\Json\Json;
15
16
/**
17
 * Class JsonExpressionBuilder builds {@see JsonExpression} for PostgreSQL DBMS.
18
 */
19
class JsonExpressionBuilder implements ExpressionBuilderInterface
20
{
21
    use ExpressionBuilderTrait;
22
23
    /**
24
     * {@inheritdoc}
25
     *
26
     * @param JsonExpression|ExpressionInterface $expression the expression to be built
27
     * @param array $params
28
     *
29
     * @return string
30
     */
31
    public function build(ExpressionInterface $expression, array &$params = []): string
32
    {
33
        $value = $expression->getValue();
0 ignored issues
show
Bug introduced by
The method getValue() does not exist on Yiisoft\Db\Expression\ExpressionInterface. It seems like you code against a sub-type of Yiisoft\Db\Expression\ExpressionInterface such as Yiisoft\Db\Pdo\PdoValue or Yiisoft\Db\Expression\ArrayExpression or Yiisoft\Db\Expression\JsonExpression or Yiisoft\Db\Query\Conditions\SimpleCondition or Yiisoft\Db\Query\Conditi...BetweenColumnsCondition. ( Ignorable by Annotation )

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

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