Completed
Push — master ( 1357ca...aa0a82 )
by Jasper
15s queued 11s
created

ResponseParser::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
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 27
     */
23
    public function __construct(DocumentParserInterface $parser)
24 27
    {
25 27
        $this->parser = $parser;
26
    }
27
28
    /**
29
     * @param \Swis\JsonApi\Client\Interfaces\TypeMapperInterface|null $typeMapper
30
     *
31
     * @return static
32 27
     */
33
    public static function create(TypeMapperInterface $typeMapper = null): self
34 27
    {
35
        return new static(DocumentParser::create($typeMapper));
36 27
    }
37 9
38 18
    /**
39 9
     * @param \Psr\Http\Message\ResponseInterface $response
40
     *
41
     * @return \Swis\JsonApi\Client\Interfaces\DocumentInterface
42 27
     */
43
    public function parse(ResponseInterface $response): DocumentInterface
44 27
    {
45
        $document = new InvalidResponseDocument();
46
47
        if ($this->responseHasBody($response)) {
48
            $document = $this->parser->parse((string) $response->getBody());
49
        } elseif ($this->responseHasSuccessfulStatusCode($response)) {
50
            $document = new Document();
51
        }
52 27
53
        $document->setResponse($response);
54 27
55
        return $document;
56
    }
57
58
    /**
59
     * @param \Psr\Http\Message\ResponseInterface $response
60
     *
61
     * @return bool
62 18
     */
63
    private function responseHasBody(ResponseInterface $response): bool
64 18
    {
65
        return (bool) $response->getBody()->getSize();
66
    }
67
68
    /**
69
     * @param \Psr\Http\Message\ResponseInterface $response
70
     *
71
     * @return bool
72
     */
73
    private function responseHasSuccessfulStatusCode(ResponseInterface $response): bool
74
    {
75
        return $response->getStatusCode() >= 200 && $response->getStatusCode() < 300;
76
    }
77
}
78