Completed
Pull Request — master (#54)
by Jasper
14:39
created

ResponseParser   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 53
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

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