Completed
Push — master ( 007584...8077f5 )
by Jonathan
10s
created

Server::getCachePath()   C

Complexity

Conditions 7
Paths 40

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7.0422

Importance

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