Completed
Push — master ( 1357ca...aa0a82 )
by Jasper
15s queued 11s
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 15
cts 15
cp 1
rs 10
c 0
b 0
f 0
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 3 1
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\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