Response::__construct()   B
last analyzed

Complexity

Conditions 8
Paths 28

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 16
nc 28
nop 1
dl 0
loc 31
rs 8.4444
c 0
b 0
f 0
1
<?php
2
namespace Javis\JsonApi;
3
4
use Javis\JsonApi\Schema\Document;
5
use Javis\JsonApi\Hydrator\ClassHydrator;
6
use Javis\JsonApi\Exceptions\ApiException;
7
8
class Response
9
{
10
    public $response;
11
    public $body;
12
    public $data;
13
    public $errors;
14
    public $meta;
15
    public $status;
16
17
    /**
18
     * @param \GuzzleHttp\Psr7\Response $response
19
     * @param bool $throwException
20
     * @return null
21
     */
22
    public function __construct($response)
23
    {
24
        $this->response = $response;
25
26
        $this->status = $this->response->getStatusCode();
27
28
        $rawResponseData = $this->response->getBody()->getContents();
29
30
        $this->body = $rawResponseData ? \json_decode($rawResponseData, true) : [];
31
32
        $this->errors = isset($this->body['errors']) ? $this->body['errors'] : [];
33
34
        if (substr($this->status, 0, 1) != 2 and !empty($this->errors)) {
35
            throw new ApiException($this->errors, $this->status);
36
        }
37
38
        //Set data
39
        if ($this->body) {
40
            //This happens when array was expected but it is empty
41
            if (empty($this->body['data'])) {
42
                $this->data = [];
43
            } else {
44
                $hydrator = new ClassHydrator();
45
                $hydrated = $hydrator->hydrate(Document::createFromArray($this->body));
46
                $this->data = $hydrated;
47
            }
48
        }
49
50
        //Set meta
51
        if (isset($this->body['meta'])) {
52
            $this->meta = $this->body['meta'];
53
        }
54
    }
55
56
57
}
58