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

Defaults::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydration\Mapping\Property;
5
6
use Stratadox\HydrationMapping\MapsProperty;
7
use Throwable;
8
9
final class Defaults implements MapsProperty
10
{
11
    private $defaultValue;
12
    private $mapping;
13
14
    private function __construct($defaultValue, MapsProperty $mapping)
15
    {
16
        $this->defaultValue = $defaultValue;
17
        $this->mapping = $mapping;
18
    }
19
20
    /**
21
     * Sets up a default value for a property mapping.
22
     *
23
     * @param mixed        $defaultValue The value to assign if the original
24
     *                                   mapping failed.
25
     * @param MapsProperty $mapping      The original mapping, to try first.
26
     * @return MapsProperty              The property mapping with default.
27
     */
28
    public static function to(
29
        $defaultValue,
30
        MapsProperty $mapping
31
    ): MapsProperty {
32
        return new self($defaultValue, $mapping);
33
    }
34
35
    /** @inheritdoc */
36
    public function name(): string
37
    {
38
        return $this->mapping->name();
39
    }
40
41
    /** @inheritdoc */
42
    public function value(array $data, $owner = null)
43
    {
44
        try {
45
            return $this->mapping->value($data, $owner);
46
        } catch (Throwable $exception) {
47
            return $this->defaultValue;
48
        }
49
    }
50
}
51