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