Completed
Push — master ( f481c9...9687e7 )
by Jesse
02:34
created

CanBeFloat::my()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydration\Mapping\Property\Scalar;
5
6
use function array_key_exists;
7
use function is_numeric;
8
use Stratadox\Hydration\Mapping\Property\MissingTheKey;
9
use Stratadox\Hydration\Mapping\Property\UnmappableProperty;
10
use Stratadox\HydrationMapping\ExposesDataKey;
11
use Stratadox\HydrationMapping\UnmappableInput;
12
13
/**
14
 * Decorates scalar type declaration with a possibly integer property.
15
 *
16
 * @package Stratadox\Hydrate
17
 * @author  Stratadox
18
 */
19
final class CanBeFloat implements ExposesDataKey
20
{
21
    private $or;
22
23
    private function __construct(ExposesDataKey $mapping)
24
    {
25
        $this->or = $mapping;
26
    }
27
28
    /**
29
     * Creates a new possibly float type wrapper.
30
     *
31
     * @param ExposesDataKey $mapping The mapping to decorate.
32
     * @return self                   The possibly float mapping.
33
     */
34
    public static function or(ExposesDataKey $mapping): self
35
    {
36
        return new self($mapping);
37
    }
38
39
    /** @inheritdoc */
40
    public function value(array $data, $owner = null)
41
    {
42
        $value = $this->my($data);
43
        if (is_numeric($value)) {
44
            return (float) $value;
45
        }
46
        try {
47
            return $this->or->value($data, $owner);
48
        } catch (UnmappableInput $exception) {
49
            throw UnmappableProperty::addAlternativeTypeInformation(
50
                'float',
51
                $exception
52
            );
53
        }
54
    }
55
56
    /** @inheritdoc */
57
    public function name(): string
58
    {
59
        return $this->or->name();
60
    }
61
62
    /** @inheritdoc */
63
    public function key(): string
64
    {
65
        return $this->or->key();
66
    }
67
68
    /** @throws UnmappableInput */
69
    private function my(array $data)
70
    {
71
        $key = $this->or->key();
72
        if (array_key_exists($key, $data)) {
73
            return $data[$key];
74
        }
75
        throw MissingTheKey::inTheInput($data, $this, $key);
76
    }
77
}
78