Completed
Push — master ( c45cef...ec5c79 )
by Jonathan
03:46
created

Server::getCachePath()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 7
Bugs 1 Features 4
Metric Value
c 7
b 1
f 4
dl 0
loc 22
ccs 14
cts 14
cp 1
rs 8.9197
cc 4
eloc 12
nc 8
nop 2
crap 4
1
<?php
2
3
namespace League\Glide;
4
5
use InvalidArgumentException;
6
use League\Flysystem\FileExistsException;
7
use League\Flysystem\FilesystemInterface;
8
use League\Glide\Api\ApiInterface;
9
use League\Glide\Filesystem\FileNotFoundException;
10
use League\Glide\Filesystem\FilesystemException;
11
use League\Glide\Responses\ResponseFactoryInterface;
12
13
class Server
14
{
15
    /**
16
     * Source file system.
17
     * @var FilesystemInterface
18
     */
19
    protected $source;
20
21
    /**
22
     * Source path prefix.
23
     * @var string
24
     */
25
    protected $sourcePathPrefix;
26
27
    /**
28
     * Cache file system.
29
     * @var FilesystemInterface
30
     */
31
    protected $cache;
32
33
    /**
34
     * Cache path prefix.
35
     * @var string
36
     */
37
    protected $cachePathPrefix;
38
39
    /**
40
     * Whether to group cache in folders.
41
     * @var bool
42
     */
43
    protected $groupCacheInFolders = true;
44
45
    /**
46
     * Image manipulation API.
47
     * @var ApiInterface
48
     */
49
    protected $api;
50
51
    /**
52
     * Response factory.
53
     * @var ResponseFactoryInterface|null
54
     */
55
    protected $responseFactory;
56
57
    /**
58
     * Base URL.
59
     * @var string
60
     */
61
    protected $baseUrl;
62
63
    /**
64
     * Default image manipulations.
65
     * @var array
66
     */
67
    protected $defaults = [];
68
69
    /**
70
     * Preset image manipulations.
71
     * @var array
72
     */
73
    protected $presets = [];
74
75
    /**
76
     * Create Server instance.
77
     * @param FilesystemInterface $source Source file system.
78
     * @param FilesystemInterface $cache  Cache file system.
79
     * @param ApiInterface        $api    Image manipulation API.
80
     */
81 141
    public function __construct(FilesystemInterface $source, FilesystemInterface $cache, ApiInterface $api)
82
    {
83 141
        $this->setSource($source);
84 141
        $this->setCache($cache);
85 141
        $this->setApi($api);
86 141
    }
87
88
    /**
89
     * Set source file system.
90
     * @param FilesystemInterface $source Source file system.
91
     */
92 141
    public function setSource(FilesystemInterface $source)
93
    {
94 141
        $this->source = $source;
95 141
    }
96
97
    /**
98
     * Get source file system.
99
     * @return FilesystemInterface Source file system.
100
     */
101 6
    public function getSource()
102
    {
103 6
        return $this->source;
104
    }
105
106
    /**
107
     * Set source path prefix.
108
     * @param string $sourcePathPrefix Source path prefix.
109
     */
110 15
    public function setSourcePathPrefix($sourcePathPrefix)
111
    {
112 15
        $this->sourcePathPrefix = trim($sourcePathPrefix, '/');
113 15
    }
114
115
    /**
116
     * Get source path prefix.
117
     * @return string Source path prefix.
118
     */
119 6
    public function getSourcePathPrefix()
120
    {
121 6
        return $this->sourcePathPrefix;
122
    }
123
124
    /**
125
     * Get source path.
126
     * @param  string                $path Image path.
127
     * @return string                The source path.
128
     * @throws FileNotFoundException
129
     */
130 66
    public function getSourcePath($path)
131
    {
132 66
        $path = trim($path, '/');
133
134 66
        if (substr($path, 0, strlen($this->baseUrl)) === $this->baseUrl) {
135 3
            $path = trim(substr($path, strlen($this->baseUrl)), '/');
136 3
        }
137
138 66
        if ($path === '') {
139 3
            throw new FileNotFoundException('Image path missing.');
140
        }
141
142 63
        if ($this->sourcePathPrefix) {
143 6
            $path = $this->sourcePathPrefix.'/'.$path;
144 6
        }
145
146 63
        return rawurldecode($path);
147
    }
148
149
    /**
150
     * Check if a source file exists.
151
     * @param  string $path Image path.
152
     * @return bool   Whether the source file exists.
153
     */
154 18
    public function sourceFileExists($path)
155
    {
156 18
        return $this->source->has($this->getSourcePath($path));
157
    }
158
159
    /**
160
     * Set base URL.
161
     * @param string $baseUrl Base URL.
162
     */
163 12
    public function setBaseUrl($baseUrl)
164
    {
165 12
        $this->baseUrl = trim($baseUrl, '/');
166 12
    }
167
168
    /**
169
     * Get base URL.
170
     * @return string Base URL.
171
     */
172 6
    public function getBaseUrl()
173
    {
174 6
        return $this->baseUrl;
175
    }
176
177
    /**
178
     * Set cache file system.
179
     * @param FilesystemInterface $cache Cache file system.
180
     */
181 141
    public function setCache(FilesystemInterface $cache)
182
    {
183 141
        $this->cache = $cache;
184 141
    }
185
186
    /**
187
     * Get cache file system.
188
     * @return FilesystemInterface Cache file system.
189
     */
190 6
    public function getCache()
191
    {
192 6
        return $this->cache;
193
    }
194
195
    /**
196
     * Set cache path prefix.
197
     * @param string $cachePathPrefix Cache path prefix.
198
     */
199 12
    public function setCachePathPrefix($cachePathPrefix)
200
    {
201 12
        $this->cachePathPrefix = trim($cachePathPrefix, '/');
202 12
    }
203
204
    /**
205
     * Get cache path prefix.
206
     * @return string Cache path prefix.
207
     */
208 6
    public function getCachePathPrefix()
209
    {
210 6
        return $this->cachePathPrefix;
211
    }
212
213
    /**
214
     * Set the group cache in folders setting.
215
     * @param bool $groupCacheInFolders Whether to group cache in folders.
216
     */
217 12
    public function setGroupCacheInFolders($groupCacheInFolders)
218
    {
219 12
        $this->groupCacheInFolders = $groupCacheInFolders;
220 12
    }
221
222
    /**
223
     * Get the group cache in folders setting.
224
     * @return bool Whether to group cache in folders.
225
     */
226 6
    public function getGroupCacheInFolders()
227
    {
228 6
        return $this->groupCacheInFolders;
229
    }
230
231
    /**
232
     * Get cache path.
233
     * @param  string $path   Image path.
234
     * @param  array  $params Image manipulation params.
235
     * @return string Cache path.
236
     */
237 48
    public function getCachePath($path, array $params = [])
238
    {
239 48
        $sourcePath = $this->getSourcePath($path);
240
241 48
        if ($this->sourcePathPrefix) {
242 3
            $sourcePath = substr($sourcePath, strlen($this->sourcePathPrefix) + 1);
243 3
        }
244
245 48
        $params = $this->getAllParams($params);
246 48
        unset($params['s'], $params['p']);
247 48
        ksort($params);
248
249 48
        $md5 = md5($sourcePath.'?'.http_build_query($params));
250
251 48
        $path = $this->groupCacheInFolders ? $sourcePath.'/'.$md5 : $md5;
252
253 48
        if ($this->cachePathPrefix) {
254 3
            $path = $this->cachePathPrefix.'/'.$path;
255 3
        }
256
257 48
        return $path;
258
    }
259
260
    /**
261
     * Check if a cache file exists.
262
     * @param  string $path   Image path.
263
     * @param  array  $params Image manipulation params.
264
     * @return bool   Whether the cache file exists.
265
     */
266 33
    public function cacheFileExists($path, array $params)
267
    {
268 33
        return $this->cache->has(
269 33
            $this->getCachePath($path, $params)
270 33
        );
271
    }
272
273
    /**
274
     * Delete cached manipulations for an image.
275
     * @param  string $path Image path.
276
     * @return bool   Whether the delete succeeded.
277
     */
278 3
    public function deleteCache($path)
279
    {
280 3
        return $this->cache->deleteDir(
281 3
            dirname($this->getCachePath($path))
282 3
        );
283
    }
284
285
    /**
286
     * Set image manipulation API.
287
     * @param ApiInterface $api Image manipulation API.
288
     */
289 141
    public function setApi(ApiInterface $api)
290
    {
291 141
        $this->api = $api;
292 141
    }
293
294
    /**
295
     * Get image manipulation API.
296
     * @return ApiInterface Image manipulation API.
297
     */
298 6
    public function getApi()
299
    {
300 6
        return $this->api;
301
    }
302
303
    /**
304
     * Set default image manipulations.
305
     * @param array $defaults Default image manipulations.
306
     */
307 15
    public function setDefaults(array $defaults)
308
    {
309 15
        $this->defaults = $defaults;
310 15
    }
311
312
    /**
313
     * Get default image manipulations.
314
     * @return array Default image manipulations.
315
     */
316 6
    public function getDefaults()
317
    {
318 6
        return $this->defaults;
319
    }
320
321
    /**
322
     * Set preset image manipulations.
323
     * @param array $presets Preset image manipulations.
324
     */
325 15
    public function setPresets(array $presets)
326
    {
327 15
        $this->presets = $presets;
328 15
    }
329
330
    /**
331
     * Get preset image manipulations.
332
     * @return array Preset image manipulations.
333
     */
334 6
    public function getPresets()
335
    {
336 6
        return $this->presets;
337
    }
338
339
    /**
340
     * Get all image manipulations params, including defaults and presets.
341
     * @param  array $params Image manipulation params.
342
     * @return array All image manipulation params.
343
     */
344 51
    public function getAllParams(array $params)
345
    {
346 51
        $all = $this->defaults;
347
348 51
        if (isset($params['p'])) {
349 3
            foreach (explode(',', $params['p']) as $preset) {
350 3
                if (isset($this->presets[$preset])) {
351 3
                    $all = array_merge($all, $this->presets[$preset]);
352 3
                }
353 3
            }
354 3
        }
355
356 51
        return array_merge($all, $params);
357
    }
358
359
    /**
360
     * Set response factory.
361
     * @param ResponseFactoryInterface|null $responseFactory Response factory.
362
     */
363 15
    public function setResponseFactory(ResponseFactoryInterface $responseFactory = null)
364
    {
365 15
        $this->responseFactory = $responseFactory;
366 15
    }
367
368
    /**
369
     * Get response factory.
370
     * @return ResponseFactoryInterface Response factory.
371
     */
372 6
    public function getResponseFactory()
373
    {
374 6
        return $this->responseFactory;
375
    }
376
377
    /**
378
     * Generate and return image response.
379
     * @param  string                   $path   Image path.
380
     * @param  array                    $params Image manipulation params.
381
     * @return mixed                    Image response.
382
     * @throws InvalidArgumentException
383
     */
384 6
    public function getImageResponse($path, array $params)
385
    {
386 6
        if (is_null($this->responseFactory)) {
387 3
            throw new InvalidArgumentException(
388
                'Unable to get image response, no response factory defined.'
389 3
            );
390
        }
391
392 3
        $path = $this->makeImage($path, $params);
393
394 3
        return $this->responseFactory->create($this->cache, $path);
395
    }
396
397
    /**
398
     * Generate and return Base64 encoded image.
399
     * @param  string              $path   Image path.
400
     * @param  array               $params Image manipulation params.
401
     * @return string              Base64 encoded image.
402
     * @throws FilesystemException
403
     */
404 6
    public function getImageAsBase64($path, array $params)
405
    {
406 6
        $path = $this->makeImage($path, $params);
407
408 6
        $source = $this->cache->read($path);
409
410 6
        if ($source === false) {
411 3
            throw new FilesystemException(
412 3
                'Could not read the image `'.$path.'`.'
413 3
            );
414
        }
415
416 3
        return 'data:'.$this->cache->getMimetype($path).';base64,'.base64_encode($source);
417
    }
418
419
    /**
420
     * Generate and output image.
421
     * @param  string                   $path   Image path.
422
     * @param  array                    $params Image manipulation params.
423
     * @throws InvalidArgumentException
424
     */
425 3
    public function outputImage($path, array $params)
426
    {
427 3
        $path = $this->makeImage($path, $params);
428
429 3
        header('Content-Type:'.$this->cache->getMimetype($path));
430 3
        header('Content-Length:'.$this->cache->getSize($path));
431 3
        header('Cache-Control:'.'max-age=31536000, public');
432 3
        header('Expires:'.date_create('+1 years')->format('D, d M Y H:i:s').' GMT');
433
434 3
        $stream = $this->cache->readStream($path);
435
436 3
        rewind($stream);
437 3
        fpassthru($stream);
438 3
        fclose($stream);
439 3
    }
440
441
    /**
442
     * Generate manipulated image.
443
     * @param  string                $path   Image path.
444
     * @param  array                 $params Image manipulation params.
445
     * @return string                Cache path.
446
     * @throws FileNotFoundException
447
     * @throws FilesystemException
448
     */
449 30
    public function makeImage($path, array $params)
450
    {
451 30
        $sourcePath = $this->getSourcePath($path);
452 30
        $cachedPath = $this->getCachePath($path, $params);
453
454 30
        if ($this->cacheFileExists($path, $params) === true) {
455 15
            return $cachedPath;
456
        }
457
458 15
        if ($this->sourceFileExists($path) === false) {
459 3
            throw new FileNotFoundException(
460 3
                'Could not find the image `'.$sourcePath.'`.'
461 3
            );
462
        }
463
464 12
        $source = $this->source->read(
465
            $sourcePath
466 12
        );
467
468 12
        if ($source === false) {
469 3
            throw new FilesystemException(
470 3
                'Could not read the image `'.$sourcePath.'`.'
471 3
            );
472
        }
473
474
        // We need to write the image to the local disk before
475
        // doing any manipulations. This is because EXIF data
476
        // can only be read from an actual file.
477 9
        $tmp = tempnam(sys_get_temp_dir(), 'Glide');
478
479 9
        if (file_put_contents($tmp, $source) === false) {
480
            throw new FilesystemException(
481
                'Unable to write temp file for `'.$sourcePath.'`.'
482
            );
483
        }
484
485
        try {
486 9
            $write = $this->cache->write(
487 9
                $cachedPath,
488 9
                $this->api->run($tmp, $this->getAllParams($params))
489 9
            );
490
491 6
            if ($write === false) {
492 3
                throw new FilesystemException(
493 3
                    'Could not write the image `'.$cachedPath.'`.'
494 3
                );
495
            }
496 9
        } catch (FileExistsException $exception) {
497
            // This edge case occurs when the target already exists
498
            // because it's currently be written to disk in another
499
            // request. It's best to just fail silently.
500
        }
501
502 6
        unlink($tmp);
503
504 6
        return $cachedPath;
505
    }
506
}
507