1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Yiisoft\Db\Pgsql\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\ArrayExpression; |
||
13 | use Yiisoft\Db\Expression\ExpressionBuilderInterface; |
||
14 | use Yiisoft\Db\Expression\ExpressionInterface; |
||
15 | use Yiisoft\Db\Expression\JsonExpression; |
||
16 | use Yiisoft\Db\QueryBuilder\QueryBuilderInterface; |
||
17 | use Yiisoft\Db\Query\QueryInterface; |
||
18 | use Yiisoft\Json\Json; |
||
19 | |||
20 | /** |
||
21 | * Builds expressions for {@see `Yiisoft\Db\Expression\JsonExpression`} for PostgreSQL Server. |
||
22 | */ |
||
23 | final class JsonExpressionBuilder implements ExpressionBuilderInterface |
||
24 | { |
||
25 | 16 | public function __construct(private QueryBuilderInterface $queryBuilder) |
|
26 | { |
||
27 | 16 | } |
|
28 | |||
29 | /** |
||
30 | * The Method builds the raw SQL from the $expression that won't be additionally escaped or quoted. |
||
31 | * |
||
32 | * @param JsonExpression $expression The expression to build. |
||
33 | * @param array $params The binding parameters. |
||
34 | * |
||
35 | * @throws Exception |
||
36 | * @throws InvalidArgumentException |
||
37 | * @throws InvalidConfigException |
||
38 | * @throws JsonException |
||
39 | * @throws NotSupportedException |
||
40 | * |
||
41 | * @return string The raw SQL that won't be additionally escaped or quoted. |
||
42 | */ |
||
43 | 16 | public function build(ExpressionInterface $expression, array &$params = []): string |
|
44 | { |
||
45 | /** @psalm-var mixed $value */ |
||
46 | 16 | $value = $expression->getValue(); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
47 | |||
48 | 16 | if ($value instanceof QueryInterface) { |
|
49 | 2 | [$sql, $params] = $this->queryBuilder->build($value, $params); |
|
50 | 2 | return "($sql)" . $this->getTypeHint($expression); |
|
51 | } |
||
52 | |||
53 | 14 | if ($value instanceof ArrayExpression) { |
|
54 | 1 | $placeholder = 'array_to_json(' . $this->queryBuilder->buildExpression($value, $params) . ')'; |
|
55 | } else { |
||
56 | 14 | $placeholder = $this->queryBuilder->bindParam(Json::encode($value), $params); |
|
57 | } |
||
58 | |||
59 | 14 | return $placeholder . $this->getTypeHint($expression); |
|
60 | } |
||
61 | |||
62 | /** |
||
63 | * @return string The typecast expression based on {@see JsonExpression::getType()}. |
||
64 | */ |
||
65 | 16 | private function getTypeHint(JsonExpression $expression): string |
|
66 | { |
||
67 | 16 | $type = $expression->getType(); |
|
68 | |||
69 | 16 | if ($type === null) { |
|
70 | 13 | return ''; |
|
71 | } |
||
72 | |||
73 | 4 | return '::' . $type; |
|
74 | } |
||
75 | } |
||
76 |