|
1
|
|
|
<?php |
|
2
|
|
|
namespace MetaHydrator\Parser; |
|
3
|
|
|
|
|
4
|
|
|
use MetaHydrator\Exception\ParsingException; |
|
5
|
|
|
use MetaHydrator\Exception\ValidationException; |
|
6
|
|
|
use MetaHydrator\Validator\ValidatorInterface; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Class ArrayParser |
|
10
|
|
|
* @package MetaHydrator\Parser |
|
11
|
|
|
*/ |
|
12
|
|
|
class ArrayParser extends AbstractParser |
|
13
|
|
|
{ |
|
14
|
|
|
/** @var ParserInterface */ |
|
15
|
|
|
private $subParser; |
|
16
|
|
|
|
|
17
|
|
|
/** @var ValidatorInterface[] */ |
|
18
|
|
|
private $subValidators; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* ArrayParser constructor. |
|
22
|
|
|
* @param ParserInterface $subParser |
|
23
|
|
|
* @param ValidatorInterface[] $subValidators |
|
24
|
|
|
* @param string $errorMessage |
|
25
|
|
|
*/ |
|
26
|
|
|
public function __construct(ParserInterface $subParser, $subValidators = [], $errorMessage = "") |
|
27
|
|
|
{ |
|
28
|
|
|
parent::__construct($errorMessage); |
|
29
|
|
|
$this->subParser = $subParser; |
|
30
|
|
|
$this->subValidators = $subValidators; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @param $rawValue |
|
35
|
|
|
* @return mixed |
|
36
|
|
|
* |
|
37
|
|
|
* @throws ParsingException |
|
38
|
|
|
*/ |
|
39
|
|
|
public function parse($rawValue) |
|
40
|
|
|
{ |
|
41
|
|
|
if ($rawValue === null) { |
|
42
|
|
|
return null; |
|
43
|
|
|
} |
|
44
|
|
|
if (!is_array($rawValue)) { |
|
45
|
|
|
$this->throw(); |
|
46
|
|
|
} |
|
47
|
|
|
$errors = []; |
|
48
|
|
|
$ko = false; |
|
49
|
|
|
$parsedArray = []; |
|
50
|
|
|
foreach ($rawValue as $key => $value) { |
|
51
|
|
|
try { |
|
52
|
|
|
$parsedValue = $this->subParser->parse($value); |
|
53
|
|
|
$this->validate($parsedValue); |
|
54
|
|
|
$parsedArray[$key] = $parsedValue; |
|
55
|
|
|
$errors[$key] = null; |
|
56
|
|
|
} catch (ValidationException $exception) { |
|
57
|
|
|
$errors[$key] = $exception->getInnerError(); |
|
58
|
|
|
$ko = true; |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
if ($ko) { |
|
63
|
|
|
throw new ParsingException($errors); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return $parsedArray; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* @param $subValue |
|
71
|
|
|
* @throws ValidationException |
|
72
|
|
|
*/ |
|
73
|
|
|
private function validate($subValue) |
|
74
|
|
|
{ |
|
75
|
|
|
foreach ($this->subValidators as $subValidator) { |
|
76
|
|
|
$subValidator->validate($subValue); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|