Passed
Pull Request — master (#752)
by Sergei
02:23
created

JsonColumnSchema   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 30
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A dbTypecast() 0 7 3
A phpTypecast() 0 7 2
A __construct() 0 7 1
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 JsonColumnSchema extends AbstractColumnSchema
15
{
16
    public function __construct(string $name)
17
    {
18
        parent::__construct($name);
19
20
        $this->dbType('json');
21
        $this->type(SchemaInterface::TYPE_JSON);
22
        $this->phpType(SchemaInterface::PHP_TYPE_ARRAY);
23
    }
24
25
    public function dbTypecast(mixed $value): mixed
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