Passed
Pull Request — master (#808)
by Sergei
02:31
created

JsonColumn::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Schema\Column;
6
7
use Yiisoft\Db\Expression\ExpressionInterface;
8
use Yiisoft\Db\Expression\JsonExpression;
9
use Yiisoft\Db\Schema\SchemaInterface;
10
11
use function is_string;
12
use function json_decode;
13
14
class JsonColumn extends Column
15
{
16
    public function __construct(
17
        string|null $type = SchemaInterface::TYPE_JSON,
18
        string|null $phpType = SchemaInterface::PHP_TYPE_ARRAY,
19
    ) {
20
        parent::__construct($type, $phpType);
21
22
        $this->dbType('json');
23
    }
24
25
    public function dbTypecast(mixed $value): ExpressionInterface|null
26
    {
27
        if ($value === null || $value instanceof ExpressionInterface) {
28
            return $value;
29
        }
30
31
        return new JsonExpression($value, $this->getDbType());
32
    }
33
34
    /**
35
     * @throws \JsonException
36
     */
37
    public function phpTypecast(mixed $value): mixed
38
    {
39
        if (is_string($value)) {
40
            return json_decode($value, true, 512, JSON_THROW_ON_ERROR);
41
        }
42
43
        return $value;
44
    }
45
}
46