PropertyParserToObject::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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