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