Passed
Push — master ( be06f7...c027e3 )
by Wilmer
08:58 queued 06:59
created

JsonExpression::getValue()   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 7
    public function __construct($value, ?string $type = null)
27
    {
28 7
        if ($value instanceof self) {
29
            $value = $value->getValue();
30
        }
31
32 7
        $this->value = $value;
33 7
        $this->type = $type;
34 7
    }
35
36
    /**
37
     * The value must be compatible with {@see \Yiisoft\Json\Json::encode()|Json::encode()} input requirements.
38
     *
39
     * @return mixed
40
     */
41 30
    public function getValue()
42
    {
43 30
        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 19
    public function getType(): ?string
56
    {
57 19
        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 2
    public function jsonSerialize()
71
    {
72 2
        $value = $this->getValue();
73 2
        if ($value instanceof QueryInterface) {
74
            throw new InvalidConfigException(
75
                'The JsonExpression class can not be serialized to JSON when the value is a QueryInterface object'
76
            );
77
        }
78
79 2
        return $value;
80
    }
81
}
82