Completed
Push — master ( 52b2ea...d5cfd4 )
by Jasper
12s queued 10s
created

LinksParser::buildLink()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 9
c 0
b 0
f 0
nc 5
nop 1
dl 0
loc 18
ccs 10
cts 10
cp 1
crap 6
rs 9.2222
1
<?php
2
3
namespace Swis\JsonApi\Client\Parsers;
4
5
use Swis\JsonApi\Client\Exceptions\ValidationException;
6
use Swis\JsonApi\Client\Link;
7
use Swis\JsonApi\Client\Links;
8
9
/**
10
 * @internal
11
 */
12
class LinksParser
13
{
14
    /**
15
     * @var \Swis\JsonApi\Client\Parsers\MetaParser
16
     */
17
    private $metaParser;
18
19
    /**
20
     * @param \Swis\JsonApi\Client\Parsers\MetaParser $metaParser
21
     */
22 618
    public function __construct(MetaParser $metaParser)
23
    {
24 618
        $this->metaParser = $metaParser;
25 618
    }
26
27
    /**
28
     * @param mixed $data
29
     *
30
     * @return \Swis\JsonApi\Client\Links
31
     */
32 108
    public function parse($data): Links
33
    {
34 108
        return new Links(
35 108
            array_map(
36 36
                function ($link) {
37 108
                    return $this->buildLink($link);
38 108
                },
39 108
                (array)$data
40
            )
41
        );
42
    }
43
44
    /**
45
     * @param mixed $data
46
     *
47
     * @return \Swis\JsonApi\Client\Link
48
     */
49 108
    private function buildLink($data): ? Link
50
    {
51 108
        if ($data === null) {
52 6
            return null;
53
        }
54
55 108
        if (is_string($data)) {
56 72
            return new Link($data);
57
        }
58
59 42
        if (!is_object($data)) {
60 24
            throw new ValidationException(sprintf('Link has to be an object, string or null, "%s" given.', gettype($data)));
61
        }
62 18
        if (!property_exists($data, 'href')) {
63 6
            throw new ValidationException('Link must have a "href" attribute.');
64
        }
65
66 12
        return new Link($data->href, property_exists($data, 'meta') ? $this->metaParser->parse($data->meta) : null);
67
    }
68
}
69