Passed
Push — master ( 03d3d0...cea9c0 )
by Alexander
07:36 queued 05:58
created

JsonExpressionBuilder::build()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 9
c 0
b 0
f 0
nc 3
nop 2
dl 0
loc 20
ccs 9
cts 9
cp 1
crap 3
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql;
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\ArrayExpression;
13
use Yiisoft\Db\Expression\ExpressionBuilderInterface;
14
use Yiisoft\Db\Expression\ExpressionBuilderTrait;
15
use Yiisoft\Db\Expression\ExpressionInterface;
16
use Yiisoft\Db\Expression\JsonExpression;
17
use Yiisoft\Db\Query\Query;
18
use Yiisoft\Db\Query\QueryInterface;
19
use Yiisoft\Json\Json;
20
21
/**
22
 * The class JsonExpressionBuilder builds {@see JsonExpression} for PostgreSQL DBMS.
23
 */
24
final class JsonExpressionBuilder implements ExpressionBuilderInterface
25
{
26
    use ExpressionBuilderTrait;
27
28
    /**
29
     * Method builds the raw SQL from the $expression that will not be additionally escaped or quoted.
30
     *
31
     * @param ExpressionInterface $expression the expression to be built.
32
     * @param array $params the binding parameters.
33
     *
34
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
35
     *
36
     * @return string the raw SQL that will not be additionally escaped or quoted.
37
     */
38 16
    public function build(ExpressionInterface $expression, array &$params = []): string
39
    {
40
        /**
41
         * @var JsonExpression $expression
42
         * @var array|mixed|QueryInterface $value
43
         */
44 16
        $value = $expression->getValue();
45
46 16
        if ($value instanceof Query) {
47 2
            [$sql, $params] = $this->queryBuilder->build($value, $params);
48 2
            return "($sql)" . $this->getTypecast($expression);
49
        }
50
51 14
        if ($value instanceof ArrayExpression) {
52 1
            $placeholder = 'array_to_json(' . $this->queryBuilder->buildExpression($value, $params) . ')';
53
        } else {
54 14
            $placeholder = $this->queryBuilder->bindParam(Json::encode($value), $params);
55
        }
56
57 14
        return $placeholder . $this->getTypecast($expression);
58
    }
59
60
    /**
61
     * @param JsonExpression $expression
62
     *
63
     * @return string the typecast expression based on {@see type}.
64
     */
65 16
    protected function getTypecast(JsonExpression $expression): string
66
    {
67 16
        if ($expression->getType() === null) {
68 13
            return '';
69
        }
70
71 4
        return '::' . (string) $expression->getType();
72
    }
73
}
74