Passed
Push — master ( 2ce9aa...37ec61 )
by Jasper
02:07
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
declare(strict_types=1);
4
5
namespace Swis\JsonApi\Client\Parsers;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Swis\JsonApi\Client\Document;
9
use Swis\JsonApi\Client\Interfaces\DocumentInterface;
10
use Swis\JsonApi\Client\Interfaces\DocumentParserInterface;
11
use Swis\JsonApi\Client\Interfaces\ResponseParserInterface;
12
use Swis\JsonApi\Client\Interfaces\TypeMapperInterface;
13
use Swis\JsonApi\Client\InvalidResponseDocument;
14
15
class ResponseParser implements ResponseParserInterface
16
{
17
    private DocumentParserInterface $parser;
18
19 32
    public function __construct(DocumentParserInterface $parser)
20
    {
21 32
        $this->parser = $parser;
22 16
    }
23
24
    /**
25
     * @return static
26
     */
27 8
    public static function create(?TypeMapperInterface $typeMapper = null): self
28
    {
29 8
        return new static(DocumentParser::create($typeMapper));
30
    }
31
32 24
    public function parse(ResponseInterface $response): DocumentInterface
33
    {
34 24
        $document = new InvalidResponseDocument;
35
36 24
        if ($this->responseHasBody($response)) {
37 12
            $document = $this->parser->parse((string) $response->getBody());
38 12
        } elseif ($this->responseHasSuccessfulStatusCode($response)) {
39 8
            $document = new Document;
40
        }
41
42 24
        $document->setResponse($response);
43
44 24
        return $document;
45
    }
46
47 24
    private function responseHasBody(ResponseInterface $response): bool
48
    {
49 24
        $body = $response->getBody();
50 24
        $size = $body->getSize();
51
52 24
        if ($size === 0) {
53 8
            return false;
54
        }
55 16
        if (is_int($size) && $size > 0) {
56 4
            return true;
57
        }
58
59 12
        if ($body->isSeekable()) {
60 4
            $pos = $body->tell();
61 4
            $chunk = $body->read(1);
62 4
            $body->seek($pos);
63
        } else {
64 8
            $chunk = $body->read(1);
65
        }
66
67 12
        return $chunk !== '';
68
    }
69
70 12
    private function responseHasSuccessfulStatusCode(ResponseInterface $response): bool
71
    {
72 12
        return $response->getStatusCode() >= 200 && $response->getStatusCode() < 300;
73
    }
74
}
75