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

CRemoteImage::getStatus()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 0
cts 0
cp 0
crap 2
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 CRemoteImage
10
{
11
    /**
12
     * Path to cache files.
13
     */
14
    private $saveFolder = null;
15
16
17
18
    /**
19
     * Use cache or not.
20
     */
21
    private $useCache = true;
22
23
24
25
    /**
26
     * HTTP object to aid in download file.
27
     */
28
    private $http;
29
30
31
32
    /**
33
     * Status of the HTTP request.
34
     */
35
    private $status;
36
37
38
39
    /**
40
     * Defalt age for cached items 60*60*24*7.
41
     */
42
    private $defaultMaxAge = 604800;
43
44
45
46
    /**
47
     * Url of downloaded item.
48
     */
49
    private $url;
50
51
52
53
    /**
54
     * Base name of cache file for downloaded item and name of image.
55
     */
56
    private $fileName;
57
58
59
60
    /**
61
     * Filename for json-file with details of cached item.
62
     */
63
    private $fileJson;
64
65
66
67
    /**
68
     * Cache details loaded from file.
69
     */
70
    private $cache;
71
72
73
74
    /**
75
     * Get status of last HTTP request.
76
     *
77
     * @return int as status
78
     */
79
    public function getStatus()
80
    {
81
        return $this->status;
82
    }
83
84
85
86
    /**
87
     * Get JSON details for cache item.
88
     *
89
     * @return array with json details on cache.
90
     */
91
    public function getDetails()
92
    {
93
        return $this->cache;
94
    }
95
96
97
98
    /**
99
     * Set the path to the cache directory.
100
     *
101
     * @param boolean $use true to use the cache and false to ignore cache.
0 ignored issues
show
Bug introduced by
There is no parameter named $use. 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 setCache($path)
106
    {
107
        $this->saveFolder = rtrim($path, "/") . "/";
108
        return $this;
109
    }
110
111
112
113
    /**
114
     * Check if cache is writable or throw exception.
115
     *
116
     * @return $this
117
     *
118
     * @throws Exception if cahce folder is not writable.
119
     */
120
    public function isCacheWritable()
121
    {
122
        if (!is_writable($this->saveFolder)) {
123
            throw new Exception("Cache folder is not writable for downloaded files.");
124
        }
125
        return $this;
126
    }
127
128
129
130
    /**
131
     * Decide if the cache should be used or not before trying to download
132
     * a remote file.
133
     *
134
     * @param boolean $use true to use the cache and false to ignore cache.
135
     *
136
     * @return $this
137
     */
138
    public function useCache($use = true)
139
    {
140
        $this->useCache = $use;
141
        return $this;
142
    }
143
144
145
146
    /**
147
     * Set header fields.
148
     *
149
     * @return $this
150
     */
151
    public function setHeaderFields()
152
    {
153
        $cimageVersion = "CImage";
154
        if (defined("CIMAGE_USER_AGENT")) {
155
            $cimageVersion = CIMAGE_USER_AGENT;
156
        }
157
        
158
        $this->http->setHeader("User-Agent", "$cimageVersion (PHP/". phpversion() . " cURL)");
159
        $this->http->setHeader("Accept", "image/jpeg,image/png,image/gif");
160
161
        if ($this->useCache) {
162
            $this->http->setHeader("Cache-Control", "max-age=0");
163
        } else {
164
            $this->http->setHeader("Cache-Control", "no-cache");
165
            $this->http->setHeader("Pragma", "no-cache");
166
        }
167
    }
168
169
170
171
    /**
172
     * Save downloaded resource to cache.
173
     *
174
     * @return string as path to saved file or false if not saved.
175
     */
176
    public function save()
177
    {
178
        $this->cache = array();
179
        $date         = $this->http->getDate(time());
180
        $maxAge       = $this->http->getMaxAge($this->defaultMaxAge);
181
        $lastModified = $this->http->getLastModified();
182
        $type         = $this->http->getContentType();
183
184
        $this->cache['Date']           = gmdate("D, d M Y H:i:s T", $date);
185
        $this->cache['Max-Age']        = $maxAge;
186
        $this->cache['Content-Type']   = $type;
187
        $this->cache['Url']            = $this->url;
188
189
        if ($lastModified) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $lastModified 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...
190
            $this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified);
191
        }
192
193
        // Save only if body is a valid image
194
        $body = $this->http->getBody();
195
        $img = imagecreatefromstring($body);
196
197
        if ($img !== false) {
198
            file_put_contents($this->fileName, $body);
199
            file_put_contents($this->fileJson, json_encode($this->cache));
200
            return $this->fileName;
201
        }
202
203
        return false;
204
    }
205
206
207
208
    /**
209
     * Got a 304 and updates cache with new age.
210
     *
211
     * @return string as path to cached file.
212
     */
213
    public function updateCacheDetails()
214
    {
215
        $date         = $this->http->getDate(time());
216
        $maxAge       = $this->http->getMaxAge($this->defaultMaxAge);
217
        $lastModified = $this->http->getLastModified();
218
219
        $this->cache['Date']    = gmdate("D, d M Y H:i:s T", $date);
220
        $this->cache['Max-Age'] = $maxAge;
221
222
        if ($lastModified) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $lastModified 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...
223
            $this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified);
224
        }
225
226
        file_put_contents($this->fileJson, json_encode($this->cache));
227
        return $this->fileName;
228
    }
229
230
231
232
    /**
233
     * Download a remote file and keep a cache of downloaded files.
234
     *
235
     * @param string $url a remote url.
236
     *
237
     * @throws Exception when status code does not match 200 or 304.
238
     *
239
     * @return string as path to downloaded file or false if failed.
240
     */
241
    public function download($url)
242
    {
243
        $this->http = new CHttpGet();
244
        $this->url = $url;
245
246
        // First check if the cache is valid and can be used
247
        $this->loadCacheDetails();
248
249
        if ($this->useCache) {
250
            $src = $this->getCachedSource();
251
            if ($src) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $src of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

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

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
252
                $this->status = 1;
253
                return $src;
254
            }
255
        }
256
257
        // Do a HTTP request to download item
258
        $this->setHeaderFields();
259
        $this->http->setUrl($this->url);
260
        $this->http->doGet();
261
262
        $this->status = $this->http->getStatus();
263
        if ($this->status === 200) {
264
            $this->isCacheWritable();
265
            return $this->save();
266
        } elseif ($this->status === 304) {
267
            $this->isCacheWritable();
268
            return $this->updateCacheDetails();
269
        }
270
271
        throw new Exception("Unknown statuscode when downloading remote image: " . $this->status);
272
    }
273
274
275
276
    /**
277
     * Get the path to the cached image file if the cache is valid.
278
     *
279
     * @return $this
280
     */
281
    public function loadCacheDetails()
282
    {
283
        $cacheFile = md5($this->url);
284
        $this->fileName = $this->saveFolder . $cacheFile;
285
        $this->fileJson = $this->fileName . ".json";
286
        if (is_readable($this->fileJson)) {
287
            $this->cache = json_decode(file_get_contents($this->fileJson), true);
288
        }
289
    }
290
291
292
293
    /**
294
     * Get the path to the cached image file if the cache is valid.
295
     *
296
     * @return string as the path ot the image file or false if no cache.
297
     */
298
    public function getCachedSource()
299
    {
300
        $imageExists = is_readable($this->fileName);
301
302
        // Is cache valid?
303
        $date   = strtotime($this->cache['Date']);
304
        $maxAge = $this->cache['Max-Age'];
305
        $now    = time();
306
        
307
        if ($imageExists && $date + $maxAge > $now) {
308
            return $this->fileName;
309
        }
310
311
        // Prepare for a 304 if available
312
        if ($imageExists && isset($this->cache['Last-Modified'])) {
313
            $this->http->setHeader("If-Modified-Since", $this->cache['Last-Modified']);
314
        }
315
316
        return false;
317
    }
318
}
319