Test Failed
Push — resize ( fbaf05...026e01 )
by Mikael
02:27
created

CHttpGet   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 285
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 5
Bugs 1 Features 1
Metric Value
c 5
b 1
f 1
dl 0
loc 285
rs 10
ccs 0
cts 112
cp 0
wmc 30
lcom 1
cbo 0

11 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
B parseHeader() 0 25 3
B doGet() 0 39 3
A getStatus() 0 6 2
A getLastModified() 0 6 2
A getContentType() 0 10 3
A getDate() 0 6 2
C getMaxAge() 0 25 7
1
<?php
2
3
namespace Mos\CImage;
4
5
/**
6
 * Get a image from a remote server using HTTP GET and If-Modified-Since.
7
 *
8
 */
9
class CHttpGet
10
{
11
    private $request  = array();
12
    private $response = array();
13
14
15
16
    /**
17
    * Constructor
18
    *
19
    */
20
    public function __construct()
21
    {
22
        $this->request['header'] = array();
23
    }
24
25
26
27
    /**
28
     * Build an encoded url.
29
     *
30
     * @param string $baseUrl This is the original url which will be merged.
31
     * @param string $merge   Thse parts should be merged into the baseUrl,
32
     *                        the format is as parse_url.
33
     *
34
     * @return string $url as the modified url.
35
     */
36
    public function buildUrl($baseUrl, $merge)
37
    {
38
        $parts = parse_url($baseUrl);
39
        $parts = array_merge($parts, $merge);
40
41
        $url  = $parts['scheme'];
42
        $url .= "://";
43
        $url .= $parts['host'];
44
        $url .= isset($parts['port'])
45
            ? ":" . $parts['port']
46
            : "" ;
47
        $url .= $parts['path'];
48
49
        return $url;
50
    }
51
52
53
54
    /**
55
     * Set the url for the request.
56
     *
57
     * @param string $url
58
     *
59
     * @return $this
60
     */
61
    public function setUrl($url)
62
    {
63
        $parts = parse_url($url);
64
        
65
        $path = "";
66
        if (isset($parts['path'])) {
67
            $pathParts = explode('/', $parts['path']);
68
            unset($pathParts[0]);
69
            foreach ($pathParts as $value) {
70
                $path .= "/" . rawurlencode($value);
71
            }
72
        }
73
        $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...
74
75
        $this->request['url'] = $url;
76
        return $this;
77
    }
78
79
80
81
    /**
82
     * Set custom header field for the request.
83
     *
84
     * @param string $field
85
     * @param string $value
86
     *
87
     * @return $this
88
     */
89
    public function setHeader($field, $value)
90
    {
91
        $this->request['header'][] = "$field: $value";
92
        return $this;
93
    }
94
95
96
97
    /**
98
     * Set header fields for the request.
99
     *
100
     * @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...
101
     * @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...
102
     *
103
     * @return $this
104
     */
105
    public function parseHeader()
106
    {
107
        //$header = explode("\r\n", rtrim($this->response['headerRaw'], "\r\n"));
108
        
109
        $rawHeaders = rtrim($this->response['headerRaw'], "\r\n");
110
        # Handle multiple responses e.g. with redirections (proxies too)
111
        $headerGroups = explode("\r\n\r\n", $rawHeaders);
112
        # We're only interested in the last one
113
        $header = explode("\r\n", end($headerGroups));
114
115
        $output = array();
116
117
        if ('HTTP' === substr($header[0], 0, 4)) {
118
            list($output['version'], $output['status']) = explode(' ', $header[0]);
119
            unset($header[0]);
120
        }
121
122
        foreach ($header as $entry) {
123
            $pos = strpos($entry, ':');
124
            $output[trim(substr($entry, 0, $pos))] = trim(substr($entry, $pos + 1));
125
        }
126
127
        $this->response['header'] = $output;
128
        return $this;
129
    }
130
131
132
133
    /**
134
     * Perform the request.
135
     *
136
     * @param boolean $debug set to true to dump headers.
137
     *
138
     * @throws Exception when curl fails to retrieve url.
139
     *
140
     * @return boolean
141
     */
142
    public function doGet($debug = false)
143
    {
144
        $options = array(
145
            CURLOPT_URL             => $this->request['url'],
146
            CURLOPT_HEADER          => 1,
147
            CURLOPT_HTTPHEADER      => $this->request['header'],
148
            CURLOPT_AUTOREFERER     => true,
149
            CURLOPT_RETURNTRANSFER  => true,
150
            CURLINFO_HEADER_OUT     => $debug,
151
            CURLOPT_CONNECTTIMEOUT  => 5,
152
            CURLOPT_TIMEOUT         => 5,
153
            CURLOPT_FOLLOWLOCATION  => true,
154
            CURLOPT_MAXREDIRS       => 2,
155
        );
156
157
        $ch = curl_init();
158
        curl_setopt_array($ch, $options);
159
        $response = curl_exec($ch);
160
161
        if (!$response) {
162
            throw new Exception("Failed retrieving url, details follows: " . curl_error($ch));
163
        }
164
165
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
166
        $this->response['headerRaw'] = substr($response, 0, $headerSize);
167
        $this->response['body']      = substr($response, $headerSize);
168
169
        $this->parseHeader();
170
171
        if ($debug) {
172
            $info = curl_getinfo($ch);
173
            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...
174
            echo "Response header (raw)<br><pre>", var_dump($this->response['headerRaw']), "</pre>";
175
            echo "Response header (parsed)<br><pre>", var_dump($this->response['header']), "</pre>";
176
        }
177
178
        curl_close($ch);
179
        return true;
180
    }
181
182
183
184
    /**
185
     * Get HTTP code of response.
186
     *
187
     * @return integer as HTTP status code or null if not available.
188
     */
189
    public function getStatus()
190
    {
191
        return isset($this->response['header']['status'])
192
            ? (int) $this->response['header']['status']
193
            : null;
194
    }
195
196
197
198
    /**
199
     * Get file modification time of response.
200
     *
201
     * @return int as timestamp.
202
     */
203
    public function getLastModified()
204
    {
205
        return isset($this->response['header']['Last-Modified'])
206
            ? strtotime($this->response['header']['Last-Modified'])
207
            : null;
208
    }
209
210
211
212
    /**
213
     * Get content type.
214
     *
215
     * @return string as the content type or null if not existing or invalid.
216
     */
217
    public function getContentType()
218
    {
219
        $type = isset($this->response['header']['Content-Type'])
220
            ? $this->response['header']['Content-Type']
221
            : null;
222
223
        return preg_match('#[a-z]+/[a-z]+#', $type)
224
            ? $type
225
            : null;
226
    }
227
228
229
230
    /**
231
     * Get file modification time of response.
232
     *
233
     * @param mixed $default as default value (int seconds) if date is
234
     *                       missing in response header.
235
     *
236
     * @return int as timestamp or $default if Date is missing in
237
     *             response header.
238
     */
239
    public function getDate($default = false)
240
    {
241
        return isset($this->response['header']['Date'])
242
            ? strtotime($this->response['header']['Date'])
243
            : $default;
244
    }
245
246
247
248
    /**
249
     * Get max age of cachable item.
250
     *
251
     * @param mixed $default as default value if date is missing in response
252
     *                       header.
253
     *
254
     * @return int as timestamp or false if not available.
255
     */
256
    public function getMaxAge($default = false)
257
    {
258
        $cacheControl = isset($this->response['header']['Cache-Control'])
259
            ? $this->response['header']['Cache-Control']
260
            : null;
261
262
        $maxAge = null;
263
        if ($cacheControl) {
264
            // max-age=2592000
265
            $part = explode('=', $cacheControl);
266
            $maxAge = ($part[0] == "max-age")
267
                ? (int) $part[1]
268
                : null;
269
        }
270
271
        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...
272
            return $maxAge;
273
        }
274
275
        $expire = isset($this->response['header']['Expires'])
276
            ? strtotime($this->response['header']['Expires'])
277
            : null;
278
279
        return $expire ? $expire : $default;
280
    }
281
282
283
284
    /**
285
     * Get body of response.
286
     *
287
     * @return string as body.
288
     */
289
    public function getBody()
290
    {
291
        return $this->response['body'];
292
    }
293
}
294