CompositeMapping::either()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 5
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\Hydration\Mapping\Composite;
4
5
use Stratadox\HydrationMapping\Mapping;
6
use Stratadox\HydrationMapping\MappingFailure;
7
use function assert;
8
9
final class CompositeMapping implements Mapping
10
{
11
    /** @var Mapping */
12
    private $mapping;
13
    /** @var Mapping */
14
    private $alternative;
15
16
    private function __construct(
17
        Mapping $mapping,
18
        Mapping $alternative
19
    ) {
20
        $this->mapping = $mapping;
21
        $this->alternative = $alternative;
22
        assert($this->mapping->name() === $this->alternative->name());
23
    }
24
25
    public static function either(
26
        Mapping $mapping,
27
        Mapping $alternative
28
    ): Mapping {
29
        return new self($mapping, $alternative);
30
    }
31
32
    public function name(): string
33
    {
34
        return $this->mapping->name();
35
    }
36
37
    public function value(array $data, $owner = null)
38
    {
39
        try {
40
            return $this->mapping->value($data, $owner);
41
        } catch (MappingFailure $firstFailure) {
42
            try {
43
                return $this->alternative->value($data, $owner);
44
            } catch (MappingFailure $secondFailure) {
45
                throw CompositeMappingFailure::both($firstFailure, $secondFailure);
46
            }
47
        }
48
    }
49
}
50