Passed
Push — master ( f4eeb8...0d22ee )
by Sergei
11:47 queued 01:39
created

JsonExpression::getType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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