Passed
Branch master (7698d8)
by Wilmer
01:29
created

ColumnSchema::dbTypecast()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

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