Completed
Pull Request — master (#3)
by Mariano
09:11
created

PropertyParserToObject   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
c 2
b 0
f 0
lcom 1
cbo 4
dl 0
loc 55
ccs 19
cts 19
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A parse() 0 9 1
A __construct() 0 6 1
A createInstanceOfTypeFromValue() 0 12 3
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