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

ResponseParser::responseHasSuccessfulStatusCode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
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