Completed
Push — master ( f2f464...1707fe )
by Andrii
16:25 queued 11:15
created

Response::getHeader()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
eloc 2
nc 2
nop 1
1
<?php
2
/**
3
 * Tools to use API as ActiveRecord for Yii2
4
 *
5
 * @link      https://github.com/hiqdev/yii2-hiart
6
 * @package   yii2-hiart
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\hiart\curl;
12
13
use hiqdev\hiart\AbstractRequest;
14
use hiqdev\hiart\AbstractResponse;
15
use hiqdev\hiart\ResponseErrorException;
16
17
/**
18
 * Class Response represents response through cURL library.
19
 */
20
class Response extends AbstractResponse
21
{
22
    /**
23
     * @var string
24
     */
25
    protected $rawData;
26
27
    /**
28
     * @var array[]
29
     */
30
    protected $headers = [];
31
32
    /**
33
     * @var string
34
     */
35
    protected $statusCode;
36
37
    /**
38
     * @var string
39
     */
40
    protected $reasonPhrase;
41
42
    /**
43
     * Response constructor.
44
     *
45
     * @param AbstractRequest $request
46
     * @param string $rawBody the raw response, returned by `curl_exec()` method
47
     * @param array $info the cURL information, returned by `curl_getinfo()` method
48
     * @param string $error the cURL error message, if present. Empty string otherwise.
49
     * @param int $errorCode the cURL error code, if present. Integer `0` otherwise.
50
     * @throws ResponseErrorException
51
     */
52
    public function __construct(AbstractRequest $request, $rawBody, $info, $error, $errorCode)
53
    {
54
        $this->request = $request;
55
56
        $this->checkTransportError($error, $errorCode);
57
58
        $parsedResponse = $this->parseRawResponse($rawBody, $info);
59
        $this->headers = $parsedResponse['headers'];
60
        $this->statusCode = $parsedResponse['statusCode'];
61
        $this->rawData = $parsedResponse['data'];
62
        $this->reasonPhrase = $parsedResponse['reasonPhrase'];
63
    }
64
65
    /**
66
     * @return mixed|string
67
     */
68
    public function getRawData()
69
    {
70
        return $this->rawData;
71
    }
72
73
    /**
74
     * @param string $name the header name
75
     * @return array|null
76
     */
77
    public function getHeader($name)
78
    {
79
        return isset($this->headers[$name]) ? $this->headers[$name] : null;
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    public function getStatusCode()
86
    {
87
        return $this->statusCode;
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93
    public function getReasonPhrase()
94
    {
95
        return $this->reasonPhrase;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->reasonPhrase; (string) is incompatible with the return type declared by the interface hiqdev\hiart\ResponseInterface::getReasonPhrase of type hiqdev\hiart\ResponseInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
96
    }
97
98
    /**
99
     * Parses raw response and returns parsed information.
100
     *
101
     * @param string $data the raw response
102
     * @param array $info the curl information (result of `gurl_getinfo` call)
103
     * @return array array with the following keys will be returned:
104
     *  - data: string, response data;
105
     *  - headers: array, response headers;
106
     *  - statusCode: string, the response status-code;
107
     *  - reasonPhrase: string, the response reason phrase (OK, NOT FOUND, etc)
108
     */
109
    protected function parseRawResponse($data, $info)
110
    {
111
        $result = [];
112
113
        $headerSize = $info['header_size'];
114
        $result['data'] = substr($data, $headerSize);
115
116
        $rawHeaders = explode("\r\n", substr($data, 0, $headerSize));
117
        // First line is status-code HTTP/1.1 200 OK
118
        list(, $result['statusCode'], $result['reasonPhrase']) = explode(' ', array_shift($rawHeaders), 3);
119
        foreach ($rawHeaders as $line) {
120
            if ($line === '') {
121
                continue;
122
            }
123
124
            list($key, $value) = explode(': ', $line);
125
            $result['headers'][$key][] = $value;
126
        }
127
128
        return $result;
129
    }
130
131
    /**
132
     * Checks $error and $errorCode for transport errors.
133
     *
134
     * @param string $error the cURL error message, if present. Empty string otherwise.
135
     * @param int $errorCode the cURL error code, if present. Integer `0` otherwise.
136
     * @throws ResponseErrorException when the error is present
137
     */
138
    protected function checkTransportError($error, $errorCode)
139
    {
140
        if ($error !== '' || $errorCode !== 0) {
141
            throw new ResponseErrorException($error, $this, $errorCode);
142
        }
143
    }
144
145
    /**
146
     * Returns array of all headers.
147
     * Key - Header name
148
     * Value - array of header values. For example:.
149
     *
150
     * ```php
151
     * ['Location' => ['http://example.com'], 'Expires' => ['Thu, 01 Jan 1970 00:00:00 GMT']]
152
     * @return array
153
     */
154
    public function getHeaders()
155
    {
156
        return $this->headers;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->headers; (array[]) is incompatible with the return type declared by the interface hiqdev\hiart\ResponseInterface::getHeaders of type string[][].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
157
    }
158
}
159