CHttpGet   A
last analyzed

Complexity

Total Complexity 30

Size/Duplication

Total Lines 285
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 285
rs 10
c 0
b 0
f 0
wmc 30
lcom 1
cbo 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A buildUrl() 0 15 2
A setUrl() 0 17 3
A setHeader() 0 5 1
A parseHeader() 0 25 3
A doGet() 0 39 3
A getStatus() 0 6 2
A getLastModified() 0 6 2
A getContentType() 0 10 3
A getDate() 0 6 2
B getMaxAge() 0 25 7
A getBody() 0 4 1
1
<?php
2
/**
3
 * Get a image from a remote server using HTTP GET and If-Modified-Since.
4
 *
5
 */
6
class CHttpGet
7
{
8
    private $request  = array();
9
    private $response = array();
10
11
12
13
    /**
14
    * Constructor
15
    *
16
    */
17
    public function __construct()
18
    {
19
        $this->request['header'] = array();
20
    }
21
22
23
24
    /**
25
     * Build an encoded url.
26
     *
27
     * @param string $baseUrl This is the original url which will be merged.
28
     * @param string $merge   Thse parts should be merged into the baseUrl,
29
     *                        the format is as parse_url.
30
     *
31
     * @return string $url as the modified url.
32
     */
33
    public function buildUrl($baseUrl, $merge)
34
    {
35
        $parts = parse_url($baseUrl);
36
        $parts = array_merge($parts, $merge);
37
38
        $url  = $parts['scheme'];
39
        $url .= "://";
40
        $url .= $parts['host'];
41
        $url .= isset($parts['port'])
42
            ? ":" . $parts['port']
43
            : "" ;
44
        $url .= $parts['path'];
45
46
        return $url;
47
    }
48
49
50
51
    /**
52
     * Set the url for the request.
53
     *
54
     * @param string $url
55
     *
56
     * @return $this
57
     */
58
    public function setUrl($url)
59
    {
60
        $parts = parse_url($url);
61
        
62
        $path = "";
63
        if (isset($parts['path'])) {
64
            $pathParts = explode('/', $parts['path']);
65
            unset($pathParts[0]);
66
            foreach ($pathParts as $value) {
67
                $path .= "/" . rawurlencode($value);
68
            }
69
        }
70
        $url = $this->buildUrl($url, array("path" => $path));
0 ignored issues
show
Documentation introduced by
array('path' => $path) is of type array<string,string,{"path":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
71
72
        $this->request['url'] = $url;
73
        return $this;
74
    }
75
76
77
78
    /**
79
     * Set custom header field for the request.
80
     *
81
     * @param string $field
82
     * @param string $value
83
     *
84
     * @return $this
85
     */
86
    public function setHeader($field, $value)
87
    {
88
        $this->request['header'][] = "$field: $value";
89
        return $this;
90
    }
91
92
93
94
    /**
95
     * Set header fields for the request.
96
     *
97
     * @param string $field
0 ignored issues
show
Bug introduced by
There is no parameter named $field. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
98
     * @param string $value
0 ignored issues
show
Bug introduced by
There is no parameter named $value. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
99
     *
100
     * @return $this
101
     */
102
    public function parseHeader()
103
    {
104
        //$header = explode("\r\n", rtrim($this->response['headerRaw'], "\r\n"));
105
        
106
        $rawHeaders = rtrim($this->response['headerRaw'], "\r\n");
107
        # Handle multiple responses e.g. with redirections (proxies too)
108
        $headerGroups = explode("\r\n\r\n", $rawHeaders);
109
        # We're only interested in the last one
110
        $header = explode("\r\n", end($headerGroups));
111
112
        $output = array();
113
114
        if ('HTTP' === substr($header[0], 0, 4)) {
115
            list($output['version'], $output['status']) = explode(' ', $header[0]);
116
            unset($header[0]);
117
        }
118
119
        foreach ($header as $entry) {
120
            $pos = strpos($entry, ':');
121
            $output[trim(substr($entry, 0, $pos))] = trim(substr($entry, $pos + 1));
122
        }
123
124
        $this->response['header'] = $output;
125
        return $this;
126
    }
127
128
129
130
    /**
131
     * Perform the request.
132
     *
133
     * @param boolean $debug set to true to dump headers.
134
     *
135
     * @throws Exception when curl fails to retrieve url.
136
     *
137
     * @return boolean
138
     */
139
    public function doGet($debug = false)
140
    {
141
        $options = array(
142
            CURLOPT_URL             => $this->request['url'],
143
            CURLOPT_HEADER          => 1,
144
            CURLOPT_HTTPHEADER      => $this->request['header'],
145
            CURLOPT_AUTOREFERER     => true,
146
            CURLOPT_RETURNTRANSFER  => true,
147
            CURLINFO_HEADER_OUT     => $debug,
148
            CURLOPT_CONNECTTIMEOUT  => 5,
149
            CURLOPT_TIMEOUT         => 5,
150
            CURLOPT_FOLLOWLOCATION  => true,
151
            CURLOPT_MAXREDIRS       => 2,
152
        );
153
154
        $ch = curl_init();
155
        curl_setopt_array($ch, $options);
156
        $response = curl_exec($ch);
157
158
        if (!$response) {
159
            throw new Exception("Failed retrieving url, details follows: " . curl_error($ch));
160
        }
161
162
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
163
        $this->response['headerRaw'] = substr($response, 0, $headerSize);
164
        $this->response['body']      = substr($response, $headerSize);
165
166
        $this->parseHeader();
167
168
        if ($debug) {
169
            $info = curl_getinfo($ch);
170
            echo "Request header<br><pre>", var_dump($info['request_header']), "</pre>";
0 ignored issues
show
Security Debugging Code introduced by
var_dump($info['request_header']); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
171
            echo "Response header (raw)<br><pre>", var_dump($this->response['headerRaw']), "</pre>";
172
            echo "Response header (parsed)<br><pre>", var_dump($this->response['header']), "</pre>";
173
        }
174
175
        curl_close($ch);
176
        return true;
177
    }
178
179
180
181
    /**
182
     * Get HTTP code of response.
183
     *
184
     * @return integer as HTTP status code or null if not available.
185
     */
186
    public function getStatus()
187
    {
188
        return isset($this->response['header']['status'])
189
            ? (int) $this->response['header']['status']
190
            : null;
191
    }
192
193
194
195
    /**
196
     * Get file modification time of response.
197
     *
198
     * @return int as timestamp.
199
     */
200
    public function getLastModified()
201
    {
202
        return isset($this->response['header']['Last-Modified'])
203
            ? strtotime($this->response['header']['Last-Modified'])
204
            : null;
205
    }
206
207
208
209
    /**
210
     * Get content type.
211
     *
212
     * @return string as the content type or null if not existing or invalid.
213
     */
214
    public function getContentType()
215
    {
216
        $type = isset($this->response['header']['Content-Type'])
217
            ? $this->response['header']['Content-Type']
218
            : null;
219
220
        return preg_match('#[a-z]+/[a-z]+#', $type)
221
            ? $type
222
            : null;
223
    }
224
225
226
227
    /**
228
     * Get file modification time of response.
229
     *
230
     * @param mixed $default as default value (int seconds) if date is
231
     *                       missing in response header.
232
     *
233
     * @return int as timestamp or $default if Date is missing in
234
     *             response header.
235
     */
236
    public function getDate($default = false)
237
    {
238
        return isset($this->response['header']['Date'])
239
            ? strtotime($this->response['header']['Date'])
240
            : $default;
241
    }
242
243
244
245
    /**
246
     * Get max age of cachable item.
247
     *
248
     * @param mixed $default as default value if date is missing in response
249
     *                       header.
250
     *
251
     * @return int as timestamp or false if not available.
252
     */
253
    public function getMaxAge($default = false)
254
    {
255
        $cacheControl = isset($this->response['header']['Cache-Control'])
256
            ? $this->response['header']['Cache-Control']
257
            : null;
258
259
        $maxAge = null;
260
        if ($cacheControl) {
261
            // max-age=2592000
262
            $part = explode('=', $cacheControl);
263
            $maxAge = ($part[0] == "max-age")
264
                ? (int) $part[1]
265
                : null;
266
        }
267
268
        if ($maxAge) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $maxAge of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
269
            return $maxAge;
270
        }
271
272
        $expire = isset($this->response['header']['Expires'])
273
            ? strtotime($this->response['header']['Expires'])
274
            : null;
275
276
        return $expire ? $expire : $default;
277
    }
278
279
280
281
    /**
282
     * Get body of response.
283
     *
284
     * @return string as body.
285
     */
286
    public function getBody()
287
    {
288
        return $this->response['body'];
289
    }
290
}
291