|
1
|
|
|
<?php |
|
2
|
|
|
namespace Mcustiel\SimpleRequest\Strategies\Properties; |
|
3
|
|
|
|
|
4
|
|
|
use Mcustiel\SimpleRequest\Exception\InvalidAnnotationException; |
|
5
|
|
|
use Mcustiel\SimpleRequest\RequestBuilder; |
|
6
|
|
|
use Mcustiel\SimpleRequest\FirstErrorRequestParser; |
|
7
|
|
|
|
|
8
|
|
|
class PropertyParserToObject extends SimplePropertyParser |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* @var \Mcustiel\SimpleRequest\RequestBuilder |
|
12
|
|
|
*/ |
|
13
|
|
|
private $requestBuilder; |
|
14
|
|
|
/** |
|
15
|
|
|
* @var string |
|
16
|
|
|
*/ |
|
17
|
|
|
private $type; |
|
18
|
|
|
|
|
19
|
4 |
|
public function __construct($name, $type, RequestBuilder $requestBuilder) |
|
20
|
|
|
{ |
|
21
|
4 |
|
parent::__construct($name); |
|
22
|
4 |
|
$this->type = $type; |
|
23
|
4 |
|
$this->requestBuilder = $requestBuilder; |
|
24
|
4 |
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* {@inheritdoc} |
|
28
|
|
|
* |
|
29
|
|
|
* @see \Mcustiel\SimpleRequest\Strategies\Properties\SimplePropertyParser::parse() |
|
30
|
|
|
*/ |
|
31
|
4 |
|
public function parse($propertyValue) |
|
32
|
|
|
{ |
|
33
|
4 |
|
$return = $this->cloneValue($propertyValue); |
|
34
|
4 |
|
$return = $this->createInstanceOfTypeFromValue($return); |
|
35
|
3 |
|
$return = $this->runFilters($return); |
|
36
|
3 |
|
$this->validate($return); |
|
37
|
|
|
|
|
38
|
3 |
|
return $return; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Parses the value as it is an instance of the class specified in type property. |
|
43
|
|
|
* |
|
44
|
|
|
* @param array|\stdClass $value The value to parse and convert to an object |
|
45
|
|
|
* |
|
46
|
|
|
* @throws \Mcustiel\SimpleRequest\Exception\InvalidAnnotationException |
|
47
|
|
|
* |
|
48
|
|
|
* @return object Parsed value as instance of class specified in type property |
|
49
|
|
|
*/ |
|
50
|
4 |
|
private function createInstanceOfTypeFromValue($value) |
|
51
|
|
|
{ |
|
52
|
4 |
|
if (!isset($value)) { |
|
53
|
1 |
|
return null; |
|
54
|
|
|
} |
|
55
|
3 |
|
if (class_exists($this->type)) { |
|
56
|
2 |
|
return $this->requestBuilder->parseRequest($value, $this->type, new FirstErrorRequestParser()); |
|
57
|
|
|
} |
|
58
|
1 |
|
throw new InvalidAnnotationException( |
|
59
|
1 |
|
"Class {$this->type} does not exist. Annotated in property {$this->name}." |
|
60
|
1 |
|
); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|