Response::__toString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Freyo\ApiGateway\Kernel\Http;
4
5
use Freyo\ApiGateway\Kernel\Support\Collection;
6
use GuzzleHttp\Psr7\Response as GuzzleResponse;
7
use Psr\Http\Message\ResponseInterface;
8
9
class Response extends GuzzleResponse
10
{
11
    /**
12
     * @return string
13
     */
14
    public function getBodyContents()
15
    {
16
        $this->getBody()->rewind();
17
        $contents = $this->getBody()->getContents();
18
        $this->getBody()->rewind();
19
20
        return $contents;
21
    }
22
23
    /**
24
     * @param \Psr\Http\Message\ResponseInterface $response
25
     *
26
     * @return \Freyo\ApiGateway\Kernel\Http\Response
27
     */
28
    public static function buildFromPsrResponse(ResponseInterface $response)
29
    {
30
        return new static(
31
            $response->getStatusCode(),
32
            $response->getHeaders(),
33
            $response->getBody(),
34
            $response->getProtocolVersion(),
35
            $response->getReasonPhrase()
36
        );
37
    }
38
39
    /**
40
     * Build to json.
41
     *
42
     * @return string
43
     */
44
    public function toJson()
45
    {
46
        return json_encode($this->toArray());
47
    }
48
49
    /**
50
     * Build to array.
51
     *
52
     * @return array
53
     */
54
    public function toArray()
55
    {
56
        $array = json_decode($this->getBodyContents(), true);
57
58
        if (JSON_ERROR_NONE === json_last_error()) {
59
            return (array) $array;
60
        }
61
62
        return [];
63
    }
64
65
    /**
66
     * Get collection data.
67
     *
68
     * @return \Freyo\ApiGateway\Kernel\Support\Collection
69
     */
70
    public function toCollection()
71
    {
72
        return new Collection($this->toArray());
73
    }
74
75
    /**
76
     * @return object
77
     */
78
    public function toObject()
79
    {
80
        return json_decode($this->toJson());
81
    }
82
83
    /**
84
     * @return bool|string
85
     */
86
    public function __toString()
87
    {
88
        return $this->getBodyContents();
89
    }
90
}