Passed
Pull Request — master (#808)
by Sergei
15:21 queued 13:01
created

BitColumn::phpTypecast()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
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\Expression;
8
use Yiisoft\Db\Expression\ExpressionInterface;
9
use Yiisoft\Db\Schema\SchemaInterface;
10
11
class BitColumn extends Column
12
{
13
    public function __construct(
14
        string|null $type = SchemaInterface::TYPE_BIT,
15
        string|null $phpType = SchemaInterface::PHP_TYPE_INTEGER,
16
    ) {
17
        parent::__construct($type, $phpType);
18
    }
19
20
    public function dbTypecast(mixed $value): int|string|ExpressionInterface|null
21
    {
22
        return match (true) {
23
            is_int($value), $value === null, $value instanceof ExpressionInterface => $value,
24
            $value === '' => null,
25
            default => (int) $value,
26
        };
27
    }
28
29
    public function phpTypecast(mixed $value): int|null
30
    {
31
        if ($value === null) {
32
            return null;
33
        }
34
35
        return (int) $value;
36
    }
37
38
    public function normalizeDefaultValue(string|null $value): int|ExpressionInterface|null
39
    {
40
        if ($value === null || $this->isComputed() || preg_match("/^\(?NULL\b/i", $value) === 1) {
41
            return null;
42
        }
43
44
        if (preg_match("/^[Bb]?'([01]+)'/", $value, $matches) === 1) {
45
            /** @var int */
46
            return bindec($matches[1]);
0 ignored issues
show
Bug Best Practice introduced by
The expression return bindec($matches[1]) could return the type double which is incompatible with the type-hinted return Yiisoft\Db\Expression\Ex...nInterface|integer|null. Consider adding an additional type-check to rule them out.
Loading history...
47
        }
48
49
        return new Expression($value);
50
    }
51
}
52