Passed
Pull Request — master (#40)
by Wilmer
14:04
created

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