Completed
Push — master ( 05aed6...998c1c )
by Jesse
05:22
created

CanBeBoolean   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 24
dl 0
loc 61
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A or() 0 6 1
A __construct() 0 8 1
A value() 0 14 4
A name() 0 3 1
A key() 0 3 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydration\Mapping\Property\Type;
5
6
use function in_array;
7
use Stratadox\Hydration\Mapping\Property\UnmappableProperty;
8
use Stratadox\HydrationMapping\ExposesDataKey;
9
use Stratadox\HydrationMapping\UnmappableInput;
10
11
/**
12
 * Decorates @see BooleanValue with custom true/false declarations.
13
 *
14
 * @package Stratadox\Hydrate
15
 * @author  Stratadox
16
 */
17
final class CanBeBoolean implements ExposesDataKey
18
{
19
    private $or;
20
    private $truths;
21
    private $falsehoods;
22
23
    private function __construct(
24
        ExposesDataKey $mapping,
25
        array $truths,
26
        array $falsehoods
27
    ) {
28
        $this->or = $mapping;
29
        $this->truths = $truths;
30
        $this->falsehoods = $falsehoods;
31
    }
32
33
    /**
34
     * Creates a new custom truth mapping, decorating a @see BooleanValue.
35
     *
36
     * @param ExposesDataKey $mapping    The mapping to decorate.
37
     * @param array          $truths     The values to consider true.
38
     * @param array          $falsehoods The values to consider false.
39
     * @return ExposesDataKey            The custom truth boolean mapping.
40
     */
41
    public static function or(
42
        ExposesDataKey $mapping,
43
        array $truths = [true, 1, '1'],
44
        array $falsehoods = [false, 0, '0']
45
    ): ExposesDataKey {
46
        return new self($mapping, $truths, $falsehoods);
47
    }
48
49
    /** @inheritdoc */
50
    public function value(array $data, $owner = null)
51
    {
52
        if (in_array($data[$this->or->key()], $this->truths, true)) {
53
            return true;
54
        }
55
        if (in_array($data[$this->or->key()], $this->falsehoods, true)) {
56
            return false;
57
        }
58
        try {
59
            return $this->or->value($data, $owner);
60
        } catch (UnmappableInput $exception) {
61
            throw UnmappableProperty::addAlternativeTypeInformation(
62
                'boolean',
63
                $exception
64
            );
65
        }
66
    }
67
68
    /** @inheritdoc */
69
    public function name(): string
70
    {
71
        return $this->or->name();
72
    }
73
74
    /** @inheritdoc */
75
    public function key(): string
76
    {
77
        return $this->or->key();
78
    }
79
}
80