Passed
Push — master ( 01c6a8...5a4258 )
by Jesse
09:00
created

BooleanMapping::value()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 10
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 14
rs 9.9332
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\Hydration\Mapping\Primitive;
4
5
use Stratadox\HydrationMapping\Mapping;
6
use function assert;
7
use function in_array;
8
9
final class BooleanMapping extends PrimitiveMapping
10
{
11
    /** @var mixed[] */
12
    private $truths = [true, 1, '1'];
13
    /** @var mixed[] */
14
    private $falsehoods = [false, 0, '0'];
15
16
    public static function custom(
17
        string $name,
18
        array $truths,
19
        array $falsehoods
20
    ): Mapping {
21
        $instance = parent::inProperty($name);
22
23
        assert($instance instanceof self);
24
        $instance->truths = $truths;
25
        $instance->falsehoods = $falsehoods;
26
27
        return $instance;
28
    }
29
30
    public function value(array $data, $owner = null): bool
31
    {
32
        $value = $this->my($data);
33
        if (in_array($value, $this->truths, true)) {
34
            return true;
35
        }
36
        if (in_array($value, $this->falsehoods, true)) {
37
            return false;
38
        }
39
        throw BooleanMappingFailure::unrecognised(
40
            $value,
41
            $this,
42
            $this->truths,
43
            $this->falsehoods
44
        );
45
    }
46
}
47