Completed
Push — master ( f8145f...0d5f93 )
by Jesse
03:38
created

CustomTruths   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 10
c 0
b 0
f 0
wmc 7

5 Methods

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