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

Defaults   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 11
dl 0
loc 39
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A name() 0 3 1
A value() 0 6 2
A __construct() 0 4 1
A to() 0 5 1
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