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

ScalarValue::inProperty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydration\Mapping\Property\Type;
5
6
use function array_key_exists;
7
use Stratadox\Hydration\Mapping\Property\MissingTheKey;
8
use Stratadox\HydrationMapping\ExposesDataKey;
9
use Stratadox\HydrationMapping\UnmappableInput;
10
11
/**
12
 * Maps the data from a single key to a scalar object property.
13
 *
14
 * @package Stratadox\Hydrate
15
 * @author  Stratadox
16
 */
17
abstract class ScalarValue implements ExposesDataKey
18
{
19
    private $name;
20
    private $key;
21
22
    private function __construct(string $name, string $dataKey)
23
    {
24
        $this->name = $name;
25
        $this->key = $dataKey;
26
    }
27
28
    /**
29
     * Creates a new mapping for the called-upon scalar type object property.
30
     *
31
     * @param string $name    The name of both the key and the property.
32
     * @return ExposesDataKey The scalar mapping object.
33
     */
34
    public static function inProperty(string $name): ExposesDataKey
35
    {
36
        return new static($name, $name);
37
    }
38
39
    /**
40
     * Creates a new mapping for the called-upon scalar type object property,
41
     * using the data from a specific key.
42
     *
43
     * @param string $name    The name of the property.
44
     * @param string $key     The array key to use.
45
     * @return ExposesDataKey The scalar mapping object.
46
     */
47
    public static function inPropertyWithDifferentKey(
48
        string $name,
49
        string $key
50
    ): ExposesDataKey {
51
        return new static($name, $key);
52
    }
53
54
    /** @inheritdoc */
55
    public function name(): string
56
    {
57
        return $this->name;
58
    }
59
60
    /** @inheritdoc */
61
    public function key(): string
62
    {
63
        return $this->key;
64
    }
65
66
    /**
67
     * Retrieves the data that is relevant for this mapping.
68
     *
69
     * @param array $data      The input data.
70
     * @return mixed           The value for our key in the input array.
71
     * @throws UnmappableInput When the key is missing in the input.
72
     */
73
    protected function my(array $data)
74
    {
75
        if (!array_key_exists($this->key(), $data)) {
76
            throw MissingTheKey::inTheInput($data, $this, $this->key());
77
        }
78
        return $data[$this->key()];
79
    }
80
}
81