Passed
Pull Request — master (#41)
by Wilmer
13:34
created

ColumnSchema::phpTypecast()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql;
6
7
use Yiisoft\Db\Expression\ExpressionInterface;
8
use Yiisoft\Db\Expression\JsonExpression;
9
use Yiisoft\Db\Schema\ColumnSchema as AbstractColumnSchema;
10
11
use function json_decode;
12
13
final class ColumnSchema extends AbstractColumnSchema
14
{
15
    /**
16
     * Converts the input value according to {@see phpType} after retrieval from the database.
17
     *
18
     * If the value is null or an {@see Expression}, it will not be converted.
19
     *
20
     * @param mixed $value input value.
21
     *
22
     * @return mixed converted value.
23
     */
24
    public function phpTypecast($value)
25
    {
26
        if ($value === null) {
27
            return;
28
        }
29
30
        if ($this->getType() === Schema::TYPE_JSON) {
31
            return json_decode($value, true, 512, JSON_THROW_ON_ERROR);
32
        }
33
34
        return parent::phpTypecast($value);
35
    }
36
37
    /**
38
     * Converts the input value according to {@see type} and {@see dbType} for use in a db query.
39
     *
40
     * If the value is null or an {@see Expression}, it will not be converted.
41
     *
42
     * @param mixed $value input value.
43
     *
44
     * @return mixed converted value. This may also be an array containing the value as the first element and the PDO
45
     * type as the second element.
46
     */
47
    public function dbTypecast($value)
48
    {
49
        if ($value === null) {
50
            return $value;
51
        }
52
53
        if ($value instanceof ExpressionInterface) {
54
            return $value;
55
        }
56
57
        if ($this->getDbType() === Schema::TYPE_JSON) {
58
            return new JsonExpression($value, $this->getType());
59
        }
60
61
        return $this->typecast($value);
62
    }
63
}
64