Passed
Push — master ( 046d68...75ea01 )
by Adrian
02:00
created

CastingManager::decimal()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Sirius\Orm;
5
6
class CastingManager
7
{
8
    protected $casts = [];
9
10
    public function register($name, callable $func)
11
    {
12
        if ( ! $name) {
13
            return; // ignore
14
        }
15
        $this->casts[$name] = $func;
16
    }
17
18
    public function cast($type, $value, ...$args)
19
    {
20
        if ($value === null) {
21
            return null;
22
        }
23
24
        if (strpos($type, ':')) {
25
            list($cast, $args) = explode(':', $type);
26
            $args = explode(',', $args);
27
        } else {
28
            $cast = $type;
29
        }
30
31
        if (method_exists($this, $cast)) {
32
            return $this->$cast($value, ...$args);
33
        }
34
35
        if (isset($this->casts[$cast])) {
36
            $func = $this->casts[$cast];
37
38
            return $func($value, ...$args);
39
        }
40
41
        return $value;
42
    }
43
44
    public function bool($value)
45
    {
46
        return ! ! $value;
47
    }
48
49
    public function int($value)
50
    {
51
        return $value === null ? null : (int)$value;
52
    }
53
54
    public function float($value)
55
    {
56
        return $value === null ? null : float($value);
0 ignored issues
show
Bug introduced by
The function float was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

56
        return $value === null ? null : /** @scrutinizer ignore-call */ float($value);
Loading history...
57
    }
58
59
    public function decimal($value, $digits)
60
    {
61
        return round((float)$value, (int)$digits);
62
    }
63
}
64