Passed
Pull Request — master (#808)
by Sergei
02:31
created

BitColumn   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 42
rs 10
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A dbTypecast() 0 9 2
A phpTypecast() 0 7 2
A __construct() 0 5 1
A normalizeDefaultValue() 0 12 5
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
use function bindec;
12
use function preg_match;
13
14
class BitColumn extends Column
15
{
16
    public function __construct(
17
        string|null $type = SchemaInterface::TYPE_BIT,
0 ignored issues
show
Bug introduced by
The constant Yiisoft\Db\Schema\SchemaInterface::TYPE_BIT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
18
        string|null $phpType = SchemaInterface::PHP_TYPE_INTEGER,
19
    ) {
20
        parent::__construct($type, $phpType);
21
    }
22
23
    public function dbTypecast(mixed $value): int|string|ExpressionInterface|null
24
    {
25
        if ($value instanceof ExpressionInterface) {
26
            return $value;
27
        }
28
29
        return match ($value) {
30
            null, '' => null,
31
            default => (int) $value,
32
        };
33
    }
34
35
    public function phpTypecast(mixed $value): int|null
36
    {
37
        if ($value === null) {
38
            return null;
39
        }
40
41
        return (int) $value;
42
    }
43
44
    public function normalizeDefaultValue(string|null $value): int|ExpressionInterface|null
45
    {
46
        if ($value === null || $this->isComputed() || preg_match("/^\(?NULL\b/i", $value) === 1) {
47
            return null;
48
        }
49
50
        if (preg_match("/^[Bb]?'([01]+)'/", $value, $matches) === 1) {
51
            /** @var int */
52
            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...
53
        }
54
55
        return new Expression($value);
56
    }
57
}
58