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

ConditionalMapping::value()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 7
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\Hydration\Mapping\Composite;
4
5
use Stratadox\Hydration\Mapping\AssertKey;
6
use Stratadox\Hydration\Mapping\Composite\ConstraintNotSatisfied;
7
use Stratadox\HydrationMapping\Mapping;
8
use Stratadox\Specification\Contract\Satisfiable;
9
10
final class ConditionalMapping implements Mapping
11
{
12
    /** @var Satisfiable */
13
    private $condition;
14
    /** @var Mapping */
15
    private $napping;
16
17
    private function __construct(Satisfiable $condition, Mapping $napping)
18
    {
19
        $this->condition = $condition;
20
        $this->napping = $napping;
21
    }
22
23
    public static function ensureThat(
24
        Satisfiable $condition,
25
        Mapping $mapping
26
    ): self {
27
        return new self($condition, $mapping);
28
    }
29
30
    public function name(): string
31
    {
32
        return $this->napping->name();
33
    }
34
35
    public function value(array $data, $owner = null)
36
    {
37
        AssertKey::exists($this, $data, $this->name());
38
        if (!$this->condition->isSatisfiedBy($data[$this->name()])) {
39
            throw ConstraintNotSatisfied::with($data[$this->name()], $this->napping, $this->condition);
40
        }
41
        return $this->napping->value($data, $owner);
42
    }
43
}
44