Completed
Push — master ( 45bee2...97600c )
by Jasper
07:14
created

ResponseParser   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 63
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A create() 0 3 1
A responseHasBody() 0 3 1
A parse() 0 13 3
A responseHasSuccessfulStatusCode() 0 3 2
1
<?php
2
3
namespace Swis\JsonApi\Client\Parsers;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Swis\JsonApi\Client\Document;
7
use Swis\JsonApi\Client\Interfaces\DocumentInterface;
8
use Swis\JsonApi\Client\Interfaces\DocumentParserInterface;
9
use Swis\JsonApi\Client\Interfaces\ResponseParserInterface;
10
use Swis\JsonApi\Client\Interfaces\TypeMapperInterface;
11
use Swis\JsonApi\Client\InvalidResponseDocument;
12
13
class ResponseParser implements ResponseParserInterface
14
{
15
    /**
16
     * @var \Swis\JsonApi\Client\Interfaces\DocumentParserInterface
17
     */
18
    private $parser;
19
20
    /**
21
     * @param \Swis\JsonApi\Client\Interfaces\DocumentParserInterface $parser
22
     */
23 45
    public function __construct(DocumentParserInterface $parser)
24
    {
25 45
        $this->parser = $parser;
26 45
    }
27
28
    /**
29
     * @param \Swis\JsonApi\Client\Interfaces\TypeMapperInterface|null $typeMapper
30
     *
31
     * @return static
32
     */
33 18
    public static function create(TypeMapperInterface $typeMapper = null): self
34
    {
35 18
        return new static(DocumentParser::create($typeMapper));
36
    }
37
38
    /**
39
     * @param \Psr\Http\Message\ResponseInterface $response
40
     *
41
     * @return \Swis\JsonApi\Client\Interfaces\DocumentInterface
42
     */
43 27
    public function parse(ResponseInterface $response): DocumentInterface
44
    {
45 27
        $document = new InvalidResponseDocument();
46
47 27
        if ($this->responseHasBody($response)) {
48 9
            $document = $this->parser->parse((string) $response->getBody());
49 18
        } elseif ($this->responseHasSuccessfulStatusCode($response)) {
50 9
            $document = new Document();
51
        }
52
53 27
        $document->setResponse($response);
54
55 27
        return $document;
56
    }
57
58
    /**
59
     * @param \Psr\Http\Message\ResponseInterface $response
60
     *
61
     * @return bool
62
     */
63 27
    private function responseHasBody(ResponseInterface $response): bool
64
    {
65 27
        return (bool) $response->getBody()->getSize();
66
    }
67
68
    /**
69
     * @param \Psr\Http\Message\ResponseInterface $response
70
     *
71
     * @return bool
72
     */
73 18
    private function responseHasSuccessfulStatusCode(ResponseInterface $response): bool
74
    {
75 18
        return $response->getStatusCode() >= 200 && $response->getStatusCode() < 300;
76
    }
77
}
78