1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Db\Expression; |
6
|
|
|
|
7
|
|
|
use JsonSerializable; |
8
|
|
|
use Yiisoft\Db\Exception\InvalidConfigException; |
9
|
|
|
use Yiisoft\Db\Query\QueryInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Represents data to encode to JSON. |
13
|
|
|
* |
14
|
|
|
* For example: |
15
|
|
|
* |
16
|
|
|
* ```php |
17
|
|
|
* new JsonExpression(['a' => 1, 'b' => 2]); // will be encoded to '{"a": 1, "b": 2}' |
18
|
|
|
* ``` |
19
|
|
|
*/ |
20
|
|
|
class JsonExpression implements ExpressionInterface, JsonSerializable |
21
|
|
|
{ |
22
|
|
|
public function __construct(protected mixed $value, private string|null $type = null) |
23
|
|
|
{ |
24
|
|
|
if ($value instanceof self) { |
25
|
|
|
$this->value = $value->getValue(); |
26
|
9 |
|
} |
27
|
|
|
} |
28
|
9 |
|
|
29
|
|
|
/** |
30
|
|
|
* The value must be compatible with {@see \json_encode()} input requirements. |
31
|
|
|
*/ |
32
|
9 |
|
public function getValue(): mixed |
33
|
9 |
|
{ |
34
|
9 |
|
return $this->value; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Type of JSON, expression should be cast to. Defaults to `null`, meaning no explicit casting will be performed. |
39
|
|
|
* |
40
|
|
|
* This property will be encountered only for DBMSs that support different types of JSON. |
41
|
31 |
|
* |
42
|
|
|
* For example, PostgresSQL has `json` and `jsonb` types. |
43
|
31 |
|
*/ |
44
|
|
|
public function getType(): string|null |
45
|
|
|
{ |
46
|
|
|
return $this->type; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Specify data which should be serialized to JSON. |
51
|
|
|
* |
52
|
|
|
* @link https://php.net/manual/en/jsonserializable.jsonserialize.php |
53
|
|
|
* |
54
|
|
|
* @throws InvalidConfigException When JsonExpression has a {@see QueryInterface} object |
55
|
20 |
|
* |
56
|
|
|
* @return mixed Data which can be serialized by `json_encode`, which is a value of any type other than a resource. |
57
|
20 |
|
*/ |
58
|
|
|
public function jsonSerialize(): mixed |
59
|
|
|
{ |
60
|
|
|
/** @psalm-var mixed $value */ |
61
|
|
|
$value = $this->getValue(); |
62
|
|
|
|
63
|
|
|
if ($value instanceof QueryInterface) { |
64
|
|
|
throw new InvalidConfigException( |
65
|
|
|
'The JsonExpression class can not be serialized to JSON when the value is a QueryInterface object.' |
66
|
|
|
); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $value; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|