/
PersonMapper.php
100 lines (85 loc) · 2.78 KB
/
PersonMapper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php declare (strict_types=1);
namespace ShipMonkTests\InputMapper\Compiler\Mapper\Object\Data;
use ShipMonk\InputMapper\Compiler\Mapper\Object\MapObject;
use ShipMonk\InputMapper\Runtime\Exception\MappingFailedException;
use ShipMonk\InputMapper\Runtime\Mapper;
use ShipMonk\InputMapper\Runtime\MapperProvider;
use ShipMonk\InputMapper\Runtime\Optional;
use function array_diff_key;
use function array_key_exists;
use function array_keys;
use function count;
use function is_array;
use function is_int;
use function is_string;
/**
* Generated mapper by {@see MapObject}. Do not edit directly.
*
* @implements Mapper<PersonInput>
*/
class PersonMapper implements Mapper
{
public function __construct(private readonly MapperProvider $provider)
{
}
/**
* @param list<string|int> $path
* @throws MappingFailedException
*/
public function map(mixed $data, array $path = []): PersonInput
{
if (!is_array($data)) {
throw MappingFailedException::incorrectType($data, $path, 'array');
}
if (!array_key_exists('id', $data)) {
throw MappingFailedException::missingKey($path, 'id');
}
if (!array_key_exists('name', $data)) {
throw MappingFailedException::missingKey($path, 'name');
}
$knownKeys = ['id' => true, 'name' => true, 'age' => true];
$extraKeys = array_diff_key($data, $knownKeys);
if (count($extraKeys) > 0) {
throw MappingFailedException::extraKeys($path, array_keys($extraKeys));
}
return new PersonInput(
$this->mapId($data['id'], [...$path, 'id']),
$this->mapName($data['name'], [...$path, 'name']),
array_key_exists('age', $data) ? $this->mapAge($data['age'], [...$path, 'age']) : Optional::none($path, 'age'),
);
}
/**
* @param list<string|int> $path
* @throws MappingFailedException
*/
private function mapId(mixed $data, array $path = []): int
{
if (!is_int($data)) {
throw MappingFailedException::incorrectType($data, $path, 'int');
}
return $data;
}
/**
* @param list<string|int> $path
* @throws MappingFailedException
*/
private function mapName(mixed $data, array $path = []): string
{
if (!is_string($data)) {
throw MappingFailedException::incorrectType($data, $path, 'string');
}
return $data;
}
/**
* @param list<string|int> $path
* @return Optional<int>
* @throws MappingFailedException
*/
private function mapAge(mixed $data, array $path = []): Optional
{
if (!is_int($data)) {
throw MappingFailedException::incorrectType($data, $path, 'int');
}
return Optional::of($data);
}
}