Passed
Push — master ( 315a8e...fda1a1 )
by Arnaud
07:50 queued 02:11
created

Asset::getImageSize()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.8437

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 0
dl 0
loc 15
ccs 5
cts 8
cp 0.625
crap 4.8437
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Cecil;
15
16
use Cecil\Asset\Image;
17
use Cecil\Builder;
18
use Cecil\Cache;
19
use Cecil\Collection\Page\Page;
20
use Cecil\Config;
21
use Cecil\Exception\ConfigException;
22
use Cecil\Exception\RuntimeException;
23
use Cecil\Url;
24
use Cecil\Util;
25
use Cecil\Util\ImageOptimizer as Optimizer;
26
use MatthiasMullie\Minify;
27
use ScssPhp\ScssPhp\Compiler;
28
use ScssPhp\ScssPhp\OutputStyle;
29
use wapmorgan\Mp3Info\Mp3Info;
30
31
/**
32
 * Asset class.
33
 *
34
 * Represents an asset (file) in the Cecil project.
35
 * Handles file locating, content reading, compiling, minifying, fingerprinting,
36
 * resizing images, and more.
37
 */
38
class Asset implements \ArrayAccess
39
{
40
    public const IMAGE_THUMB = 'thumbnails';
41
42
    /** @var Builder */
43
    protected $builder;
44
45
    /** @var Config */
46
    protected $config;
47
48
    /** @var array */
49
    protected $data = [];
50
51
    /** @var array Cache tags */
52
    protected $cacheTags = [];
53
54
    /**
55
     * Creates an Asset from a file path, an array of files path or an URL.
56
     * Options:
57
     * [
58
     *     'filename' => <string>,
59
     *     'leading_slash' => <bool>
60
     *     'ignore_missing' => <bool>,
61
     *     'fingerprint' => <bool>,
62
     *     'minify' => <bool>,
63
     *     'optimize' => <bool>,
64
     *     'fallback' => <string>,
65
     *     'useragent' => <string>,
66
     * ]
67
     *
68
     * @param Builder      $builder
69
     * @param string|array $paths
70
     * @param array|null   $options
71
     *
72
     * @throws RuntimeException
73
     */
74 1
    public function __construct(Builder $builder, string|array $paths, array|null $options = null)
75
    {
76 1
        $this->builder = $builder;
77 1
        $this->config = $builder->getConfig();
78 1
        $paths = \is_array($paths) ? $paths : [$paths];
79
        // checks path(s)
80 1
        array_walk($paths, function ($path) {
81
            // must be a string
82 1
            if (!\is_string($path)) {
83
                throw new RuntimeException(\sprintf('The path of an asset must be a string ("%s" given).', \gettype($path)));
84
            }
85
            // can't be empty
86 1
            if (empty($path)) {
87
                throw new RuntimeException('The path of an asset can\'t be empty.');
88
            }
89
            // can't be relative
90 1
            if (substr($path, 0, 2) == '..') {
91
                throw new RuntimeException(\sprintf('The path of asset "%s" is wrong: it must be directly relative to `assets` or `static` directory, or a remote URL.', $path));
92
            }
93 1
        });
94 1
        $this->data = [
95 1
            'file'     => '',    // absolute file path
96 1
            'files'    => [],    // array of absolute files path
97 1
            'missing'  => false, // if file not found but missing allowed: 'missing' is true
98 1
            '_path'    => '',    // original path
99 1
            'path'     => '',    // public path
100 1
            'url'      => null,  // URL if it's a remote file
101 1
            'ext'      => '',    // file extension
102 1
            'type'     => '',    // file type (e.g.: image, audio, video, etc.)
103 1
            'subtype'  => '',    // file media type (e.g.: image/png, audio/mp3, etc.)
104 1
            'size'     => 0,     // file size (in bytes)
105 1
            'width'    => 0,     // image width (in pixels)
106 1
            'height'   => 0,     // image height (in pixels)
107 1
            'exif'     => [],    // image exif data
108 1
            'content'  => '',    // file content
109 1
            'hash'     => '',    // file content hash (md5)
110 1
        ];
111
112
        // handles options
113 1
        $options = array_merge(
114 1
            [
115 1
                'filename'       => '',
116 1
                'leading_slash'  => true,
117 1
                'ignore_missing' => false,
118 1
                'fingerprint'    => $this->config->isEnabled('assets.fingerprint'),
119 1
                'minify'         => $this->config->isEnabled('assets.minify'),
120 1
                'optimize'       => $this->config->isEnabled('assets.images.optimize'),
121 1
                'fallback'       => '',
122 1
                'useragent'      => (string) $this->config->get('assets.remote.useragent.default'),
123 1
            ],
124 1
            \is_array($options) ? $options : []
125 1
        );
126
127
        // cache
128 1
        $cache = new Cache($this->builder, 'assets');
129 1
        $locateCacheKey = \sprintf('%s_locate__%s__%s', $options['filename'] ?: implode('_', $paths), $this->builder->getBuildId(), $this->builder->getVersion());
130
131
        // locate file(s) and get content
132 1
        if (!$cache->has($locateCacheKey)) {
133 1
            $pathsCount = \count($paths);
134 1
            for ($i = 0; $i < $pathsCount; $i++) {
135
                try {
136 1
                    $this->data['missing'] = false;
137 1
                    $locate = $this->locateFile($paths[$i], $options['fallback'], $options['useragent']);
138 1
                    $file = $locate['file'];
139 1
                    $path = $locate['path'];
140 1
                    $type = Util\File::getMediaType($file)[0];
141 1
                    if ($i > 0) { // bundle
142 1
                        if ($type != $this->data['type']) {
143
                            throw new RuntimeException(\sprintf('Asset bundle type error (%s != %s).', $type, $this->data['type']));
144
                        }
145
                    }
146 1
                    $this->data['file'] = $file;
147 1
                    $this->data['files'][] = $file;
148 1
                    $this->data['path'] = $path;
149 1
                    $this->data['url'] = Util\File::isRemote($paths[$i]) ? $paths[$i] : null;
150 1
                    $this->data['ext'] = Util\File::getExtension($file);
151 1
                    $this->data['type'] = $type;
152 1
                    $this->data['subtype'] = Util\File::getMediaType($file)[1];
153 1
                    $this->data['size'] += filesize($file);
154 1
                    $this->data['content'] .= Util\File::fileGetContents($file);
155 1
                    $this->data['hash'] = hash('md5', $this->data['content']);
156
                    // bundle default filename
157 1
                    $filename = $options['filename'];
158 1
                    if ($pathsCount > 1 && empty($filename)) {
159 1
                        switch ($this->data['ext']) {
160 1
                            case 'scss':
161 1
                            case 'css':
162 1
                                $filename = 'styles.css';
163 1
                                break;
164 1
                            case 'js':
165 1
                                $filename = 'scripts.js';
166 1
                                break;
167
                            default:
168
                                throw new RuntimeException(\sprintf('Asset bundle supports %s files only.', '.scss, .css and .js'));
169
                        }
170
                    }
171
                    // apply bundle filename to path
172 1
                    if (!empty($filename)) {
173 1
                        $this->data['path'] = $filename;
174
                    }
175
                    // add leading slash
176 1
                    if ($options['leading_slash']) {
177 1
                        $this->data['path'] = '/' . ltrim($this->data['path'], '/');
178
                    }
179 1
                    $this->data['_path'] = $this->data['path'];
180 1
                } catch (RuntimeException $e) {
181 1
                    if ($options['ignore_missing']) {
182 1
                        $this->data['missing'] = true;
183 1
                        continue;
184
                    }
185
                    throw new RuntimeException(
186
                        \sprintf('Can\'t handle asset "%s".', $paths[$i]),
187
                        previous: $e
188
                    );
189
                }
190
            }
191 1
            $cache->set($locateCacheKey, $this->data);
192
        }
193 1
        $this->data = $cache->get($locateCacheKey);
194
195
        // missing
196 1
        if ($this->data['missing']) {
197 1
            return;
198
        }
199
200
        // cache
201 1
        $cache = new Cache($this->builder, 'assets');
202
        // create cache tags from options
203 1
        $this->cacheTags = $options;
204
        // remove unnecessary cache tags
205 1
        unset($this->cacheTags['optimize'], $this->cacheTags['ignore_missing'], $this->cacheTags['fallback'], $this->cacheTags['useragent']);
206 1
        if (!\in_array($this->data['ext'], ['css', 'js', 'scss'])) {
207 1
            unset($this->cacheTags['minify']);
208
        }
209
        // optimize image?
210 1
        $optimize = false;
211 1
        if ($options['optimize'] && $this->data['type'] == 'image' && !$this->isImageInCdn()) {
212 1
            $optimize = true;
213 1
            $quality = (int) $this->config->get('assets.images.quality');
214 1
            $this->cacheTags['quality'] = $quality;
215
        }
216 1
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
217 1
        if (!$cache->has($cacheKey)) {
218
            // fingerprinting
219 1
            if ($options['fingerprint']) {
220
                $this->doFingerprint();
221
            }
222
            // compiling Sass files
223 1
            $this->doCompile();
224
            // minifying (CSS and JavaScript files)
225 1
            if ($options['minify']) {
226
                $this->doMinify();
227
            }
228
            // get image width, height and exif
229 1
            if ($this->data['type'] == 'image') {
230 1
                $this->data['width'] = $this->getWidth();
231 1
                $this->data['height'] = $this->getHeight();
232 1
                if ($this->data['subtype'] == 'image/jpeg') {
233 1
                    $this->data['exif'] = Util\File::readExif($this->data['file']);
234
                }
235
            }
236 1
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
237 1
            $this->builder->getLogger()->debug(\sprintf('Asset cached: "%s"', $this->data['path']));
238
            // optimizing images files (in cache directory)
239 1
            if ($optimize) {
240 1
                $this->optimize($cache->getContentFilePathname($this->data['path']), $this->data['path'], $quality);
241
            }
242
        }
243 1
        $this->data = $cache->get($cacheKey);
244
    }
245
246
    /**
247
     * Returns path.
248
     */
249 1
    public function __toString(): string
250
    {
251 1
        $this->save();
252
253 1
        if ($this->isImageInCdn()) {
254
            return $this->buildImageCdnUrl();
255
        }
256
257 1
        if ($this->builder->getConfig()->isEnabled('canonicalurl')) {
258
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
259
        }
260
261 1
        return $this->data['path'];
262
    }
263
264
    /**
265
     * Compiles a SCSS + cache.
266
     *
267
     * @throws RuntimeException
268
     */
269 1
    public function compile(): self
270
    {
271 1
        $this->cacheTags['compile'] = true;
272 1
        $cache = new Cache($this->builder, 'assets');
273 1
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
274 1
        if (!$cache->has($cacheKey)) {
275 1
            $this->doCompile();
276 1
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
277
        }
278 1
        $this->data = $cache->get($cacheKey);
279
280 1
        return $this;
281
    }
282
283
    /**
284
     * Minifying a CSS or a JS.
285
     */
286 1
    public function minify(): self
287
    {
288 1
        $this->cacheTags['minify'] = true;
289 1
        $cache = new Cache($this->builder, 'assets');
290 1
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
291 1
        if (!$cache->has($cacheKey)) {
292 1
            $this->doMinify();
293 1
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
294
        }
295 1
        $this->data = $cache->get($cacheKey);
296
297 1
        return $this;
298
    }
299
300
    /**
301
     * Add hash to the file name + cache.
302
     */
303 1
    public function fingerprint(): self
304
    {
305 1
        $this->cacheTags['fingerprint'] = true;
306 1
        $cache = new Cache($this->builder, 'assets');
307 1
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
308 1
        if (!$cache->has($cacheKey)) {
309 1
            $this->doFingerprint();
310 1
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
311
        }
312 1
        $this->data = $cache->get($cacheKey);
313
314 1
        return $this;
315
    }
316
317
    /**
318
     * Scales down an image to a new $width.
319
     *
320
     * @throws RuntimeException
321
     */
322 1
    public function resize(int $width): self
323
    {
324 1
        $this->checkImage();
325
326
        // if the image is already smaller than the requested width, return it
327 1
        if ($width >= $this->data['width']) {
328 1
            return $this;
329
        }
330
331 1
        $assetResized = clone $this;
332 1
        $assetResized->data['width'] = $width;
333
334 1
        if ($this->isImageInCdn()) {
335
            $assetResized->data['height'] = round($this->data['height'] / ($this->data['width'] / $width));
336
337
            return $assetResized; // returns asset with the new dimensions only: CDN do the rest of the job
338
        }
339
340 1
        $quality = (int) $this->config->get('assets.images.quality');
341
342 1
        $cache = new Cache($this->builder, 'assets');
343 1
        $assetResized->cacheTags['quality'] = $quality;
344 1
        $assetResized->cacheTags['width'] = $width;
345 1
        $cacheKey = $cache->createKeyFromAsset($assetResized, $assetResized->cacheTags);
346 1
        if (!$cache->has($cacheKey)) {
347 1
            $assetResized->data['content'] = Image::resize($assetResized, $width, $quality);
348 1
            $assetResized->data['path'] = '/' . Util::joinPath(
349 1
                (string) $this->config->get('assets.target'),
350 1
                self::IMAGE_THUMB,
351 1
                (string) $width,
352 1
                $assetResized->data['path']
353 1
            );
354 1
            $assetResized->data['path'] = $this->deduplicateThumbPath($assetResized->data['path']);
355 1
            $assetResized->data['height'] = $assetResized->getHeight();
356 1
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
357
358 1
            $cache->set($cacheKey, $assetResized->data, $this->config->get('cache.assets.ttl'));
359 1
            $this->builder->getLogger()->debug(\sprintf('Asset resized: "%s" (%sx)', $assetResized->data['path'], $width));
360
        }
361 1
        $assetResized->data = $cache->get($cacheKey);
362
363 1
        return $assetResized;
364
    }
365
366
    /**
367
     * Crops the image to the specified width and height, keeping the specified position.
368
     *
369
     * @throws RuntimeException
370
     */
371 1
    public function cover(int $width, int $height): self
372
    {
373 1
        $this->checkImage();
374
375 1
        $assetResized = clone $this;
376 1
        $assetResized->data['width'] = $width;
377 1
        $assetResized->data['height'] = $height;
378
379 1
        $quality = (int) $this->config->get('assets.images.quality');
380
381 1
        $cache = new Cache($this->builder, 'assets');
382 1
        $assetResized->cacheTags['quality'] = $quality;
383 1
        $assetResized->cacheTags['width'] = $width;
384 1
        $assetResized->cacheTags['height'] = $height;
385 1
        $cacheKey = $cache->createKeyFromAsset($assetResized, $assetResized->cacheTags);
386 1
        if (!$cache->has($cacheKey)) {
387 1
            $assetResized->data['content'] = Image::cover($assetResized, $width, $height, $quality);
388 1
            $assetResized->data['path'] = '/' . Util::joinPath(
389 1
                (string) $this->config->get('assets.target'),
390 1
                self::IMAGE_THUMB,
391 1
                (string) $width . 'x' . (string) $height,
392 1
                $assetResized->data['path']
393 1
            );
394 1
            $assetResized->data['path'] = $this->deduplicateThumbPath($assetResized->data['path']);
395 1
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
396
397 1
            $cache->set($cacheKey, $assetResized->data, $this->config->get('cache.assets.ttl'));
398 1
            $this->builder->getLogger()->debug(\sprintf('Asset resized: "%s" (%sx%s)', $assetResized->data['path'], $width, $height));
399
        }
400 1
        $assetResized->data = $cache->get($cacheKey);
401
402 1
        return $assetResized;
403
    }
404
405
    /**
406
     * Creates a maskable image (with a padding = 20%).
407
     *
408
     * @throws RuntimeException
409
     */
410
    public function maskable(?int $padding = null): self
411
    {
412
        $this->checkImage();
413
414
        if ($padding === null) {
415
            $padding = 20; // default padding
416
        }
417
418
        $assetMaskable = clone $this;
419
420
        $quality = (int) $this->config->get('assets.images.quality');
421
422
        $cache = new Cache($this->builder, 'assets');
423
        $assetMaskable->cacheTags['maskable'] = true;
424
        $cacheKey = $cache->createKeyFromAsset($assetMaskable, $assetMaskable->cacheTags);
425
        if (!$cache->has($cacheKey)) {
426
            $assetMaskable->data['content'] = Image::maskable($assetMaskable, $quality, $padding);
427
            $assetMaskable->data['path'] = '/' . Util::joinPath(
428
                (string) $this->config->get('assets.target'),
429
                'maskable',
430
                $assetMaskable->data['path']
431
            );
432
            $assetMaskable->data['size'] = \strlen($assetMaskable->data['content']);
433
434
            $cache->set($cacheKey, $assetMaskable->data, $this->config->get('cache.assets.ttl'));
435
            $this->builder->getLogger()->debug(\sprintf('Asset maskabled: "%s"', $assetMaskable->data['path']));
436
        }
437
        $assetMaskable->data = $cache->get($cacheKey);
438
439
        return $assetMaskable;
440
    }
441
442
    /**
443
     * Converts an image asset to $format format.
444
     *
445
     * @throws RuntimeException
446
     */
447 1
    public function convert(string $format, ?int $quality = null): self
448
    {
449 1
        if ($this->data['type'] != 'image') {
450
            throw new RuntimeException(\sprintf('Not able to convert "%s" (%s) to %s: not an image.', $this->data['path'], $this->data['type'], $format));
451
        }
452
453 1
        if ($quality === null) {
454 1
            $quality = (int) $this->config->get('assets.images.quality');
455
        }
456
457 1
        $asset = clone $this;
458 1
        $asset['ext'] = $format;
459 1
        $asset->data['subtype'] = "image/$format";
460
461 1
        if ($this->isImageInCdn()) {
462
            return $asset; // returns the asset with the new extension only: CDN do the rest of the job
463
        }
464
465 1
        $cache = new Cache($this->builder, 'assets');
466 1
        $this->cacheTags['quality'] = $quality;
467 1
        if ($this->data['width']) {
468 1
            $this->cacheTags['width'] = $this->data['width'];
469
        }
470 1
        $cacheKey = $cache->createKeyFromAsset($asset, $this->cacheTags);
471 1
        if (!$cache->has($cacheKey)) {
472 1
            $asset->data['content'] = Image::convert($asset, $format, $quality);
473
            $asset->data['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']);
474
            $asset->data['size'] = \strlen($asset->data['content']);
475
            $cache->set($cacheKey, $asset->data, $this->config->get('cache.assets.ttl'));
476
            $this->builder->getLogger()->debug(\sprintf('Asset converted: "%s" (%s -> %s)', $asset->data['path'], $this->data['ext'], $format));
477
        }
478
        $asset->data = $cache->get($cacheKey);
479
480
        return $asset;
481
    }
482
483
    /**
484
     * Converts an image asset to WebP format.
485
     *
486
     * @throws RuntimeException
487
     */
488
    public function webp(?int $quality = null): self
489
    {
490
        return $this->convert('webp', $quality);
491
    }
492
493
    /**
494
     * Converts an image asset to AVIF format.
495
     *
496
     * @throws RuntimeException
497
     */
498
    public function avif(?int $quality = null): self
499
    {
500
        return $this->convert('avif', $quality);
501
    }
502
503
    /**
504
     * Implements \ArrayAccess.
505
     */
506 1
    #[\ReturnTypeWillChange]
507
    public function offsetSet($offset, $value): void
508
    {
509 1
        if (!\is_null($offset)) {
510 1
            $this->data[$offset] = $value;
511
        }
512
    }
513
514
    /**
515
     * Implements \ArrayAccess.
516
     */
517 1
    #[\ReturnTypeWillChange]
518
    public function offsetExists($offset): bool
519
    {
520 1
        return isset($this->data[$offset]);
521
    }
522
523
    /**
524
     * Implements \ArrayAccess.
525
     */
526
    #[\ReturnTypeWillChange]
527
    public function offsetUnset($offset): void
528
    {
529
        unset($this->data[$offset]);
530
    }
531
532
    /**
533
     * Implements \ArrayAccess.
534
     */
535 1
    #[\ReturnTypeWillChange]
536
    public function offsetGet($offset)
537
    {
538 1
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
539
    }
540
541
    /**
542
     * Hashing content of an asset with the specified algo, sha384 by default.
543
     * Used for SRI (Subresource Integrity).
544
     *
545
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
546
     */
547 1
    public function getIntegrity(string $algo = 'sha384'): string
548
    {
549 1
        return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
550
    }
551
552
    /**
553
     * Returns MP3 file infos.
554
     *
555
     * @see https://github.com/wapmorgan/Mp3Info
556
     */
557 1
    public function getAudio(): Mp3Info
558
    {
559 1
        if ($this->data['type'] !== 'audio') {
560
            throw new RuntimeException(\sprintf('Not able to get audio infos of "%s".', $this->data['path']));
561
        }
562
563 1
        return new Mp3Info($this->data['file']);
564
    }
565
566
    /**
567
     * Returns MP4 file infos:
568
     * - duration (in seconds)
569
     * - width (in pixels)
570
     * - height (in pixels)
571
     */
572 1
    public function getVideo(): array
573
    {
574 1
        if ($this->data['type'] !== 'video') {
575
            throw new RuntimeException(\sprintf('Not able to get video infos of "%s".', $this->data['path']));
576
        }
577
578 1
        $getID3 = new \getID3();
579 1
        $videoInfos = $getID3->analyze($this->data['file']);
580
581 1
        return [
582 1
            'duration' => $videoInfos['playtime_seconds'] ?? 0,
583 1
            'width'    => $videoInfos['video']['resolution_x'] ?? 0,
584 1
            'height'   => $videoInfos['video']['resolution_y'] ?? 0,
585 1
        ];
586
    }
587
588
    /**
589
     * Returns the Data URL (encoded in Base64).
590
     *
591
     * @throws RuntimeException
592
     */
593 1
    public function dataurl(): string
594
    {
595 1
        if ($this->data['type'] == 'image' && !Image::isSVG($this)) {
596 1
            return Image::getDataUrl($this, (int) $this->config->get('assets.images.quality'));
597
        }
598
599 1
        return \sprintf('data:%s;base64,%s', $this->data['subtype'], base64_encode($this->data['content']));
600
    }
601
602
    /**
603
     * Adds asset path to the list of assets to save.
604
     *
605
     * @throws RuntimeException
606
     */
607 1
    public function save(): void
608
    {
609 1
        if ($this->data['missing']) {
610 1
            return;
611
        }
612
613 1
        $cache = new Cache($this->builder, 'assets');
614 1
        if (empty($this->data['path']) || !Util\File::getFS()->exists($cache->getContentFilePathname($this->data['path']))) {
615
            throw new RuntimeException(
616
                \sprintf('Can\'t add "%s" to assets list. Please clear cache and retry.', $this->data['path'])
617
            );
618
        }
619
620 1
        $this->builder->addAsset($this->data['path']);
621
    }
622
623
    /**
624
     * Is the asset an image and is it in CDN?
625
     */
626 1
    public function isImageInCdn(): bool
627
    {
628
        if (
629 1
            $this->data['type'] == 'image'
630 1
            && $this->config->isEnabled('assets.images.cdn')
631 1
            && $this->data['ext'] != 'ico'
632 1
            && (Image::isSVG($this) && $this->config->isEnabled('assets.images.cdn.svg'))
633
        ) {
634
            return true;
635
        }
636
        // handle remote image?
637 1
        if ($this->data['url'] !== null && $this->config->isEnabled('assets.images.cdn.remote')) {
638
            return true;
639
        }
640
641 1
        return false;
642
    }
643
644
    /**
645
     * Builds a relative path from a URL.
646
     * Used for remote files.
647
     */
648 1
    public static function buildPathFromUrl(string $url): string
649
    {
650 1
        $host = parse_url($url, PHP_URL_HOST);
651 1
        $path = parse_url($url, PHP_URL_PATH);
652 1
        $query = parse_url($url, PHP_URL_QUERY);
653 1
        $ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
654
655
        // Google Fonts hack
656 1
        if (Util\Str::endsWith($path, '/css') || Util\Str::endsWith($path, '/css2')) {
657 1
            $ext = 'css';
658
        }
659
660 1
        return Page::slugify(\sprintf('%s%s%s%s', $host, self::sanitize($path), $query ? "-$query" : '', $query && $ext ? ".$ext" : ''));
661
    }
662
663
    /**
664
     * Replaces some characters by '_'.
665
     */
666 1
    public static function sanitize(string $string): string
667
    {
668 1
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
669
    }
670
671
    /**
672
     * Compiles a SCSS.
673
     *
674
     * @throws RuntimeException
675
     */
676 1
    protected function doCompile(): self
677
    {
678
        // abort if not a SCSS file
679 1
        if ($this->data['ext'] != 'scss') {
680 1
            return $this;
681
        }
682 1
        $scssPhp = new Compiler();
683
        // import paths
684 1
        $importDir = [];
685 1
        $importDir[] = Util::joinPath($this->config->getStaticPath());
686 1
        $importDir[] = Util::joinPath($this->config->getAssetsPath());
687 1
        $scssDir = (array) $this->config->get('assets.compile.import');
688 1
        $themes = $this->config->getTheme() ?? [];
689 1
        foreach ($scssDir as $dir) {
690 1
            $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir);
691 1
            $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir);
692 1
            $importDir[] = Util::joinPath(\dirname($this->data['file']), $dir);
693 1
            foreach ($themes as $theme) {
694 1
                $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir"));
695 1
                $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir"));
696
            }
697
        }
698 1
        $scssPhp->setQuietDeps(true);
699 1
        $scssPhp->setImportPaths(array_unique($importDir));
700
        // adds source map
701 1
        if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
702
            $importDir = [];
703
            $assetDir = (string) $this->config->get('assets.dir');
704
            $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR . $assetDir . DIRECTORY_SEPARATOR);
705
            $fileRelPath = substr($this->data['file'], $assetDirPos + 8);
706
            $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath);
707
            $importDir[] = \dirname($filePath);
708
            foreach ($scssDir as $dir) {
709
                $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir);
710
            }
711
            $scssPhp->setImportPaths(array_unique($importDir));
712
            $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE);
713
            $scssPhp->setSourceMapOptions([
714
                'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()),
715
                'sourceRoot'        => '/',
716
            ]);
717
        }
718
        // defines output style
719 1
        $outputStyles = ['expanded', 'compressed'];
720 1
        $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
721 1
        if (!\in_array($outputStyle, $outputStyles)) {
722
            throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
723
        }
724 1
        $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
725
        // set variables
726 1
        $variables = $this->config->get('assets.compile.variables');
727 1
        if (!empty($variables)) {
728 1
            $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
729 1
            $scssPhp->replaceVariables($variables);
730
        }
731
        // debug
732 1
        if ($this->builder->isDebug()) {
733 1
            $scssPhp->setQuietDeps(false);
734 1
            $this->builder->getLogger()->debug(\sprintf("SCSS compiler imported paths:\n%s", Util\Str::arrayToList(array_unique($importDir))));
735
        }
736
        // update data
737 1
        $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']);
738 1
        $this->data['ext'] = 'css';
739 1
        $this->data['type'] = 'text';
740 1
        $this->data['subtype'] = 'text/css';
741 1
        $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss();
742 1
        $this->data['size'] = \strlen($this->data['content']);
743
744 1
        $this->builder->getLogger()->debug(\sprintf('Asset compiled: "%s"', $this->data['path']));
745
746 1
        return $this;
747
    }
748
749
    /**
750
     * Minifying a CSS or a JS + cache.
751
     *
752
     * @throws RuntimeException
753
     */
754 1
    protected function doMinify(): self
755
    {
756
        // compile SCSS files
757 1
        if ($this->data['ext'] == 'scss') {
758
            $this->doCompile();
759
        }
760
        // abort if already minified
761 1
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
762
            return $this;
763
        }
764
        // abord if not a CSS or JS file
765 1
        if (!\in_array($this->data['ext'], ['css', 'js'])) {
766
            return $this;
767
        }
768
        // in debug mode: disable minify to preserve inline source map
769 1
        if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
770
            return $this;
771
        }
772 1
        switch ($this->data['ext']) {
773 1
            case 'css':
774 1
                $minifier = new Minify\CSS($this->data['content']);
775 1
                break;
776 1
            case 'js':
777 1
                $minifier = new Minify\JS($this->data['content']);
778 1
                break;
779
            default:
780
                throw new RuntimeException(\sprintf('Not able to minify "%s".', $this->data['path']));
781
        }
782 1
        $this->data['content'] = $minifier->minify();
783 1
        $this->data['size'] = \strlen($this->data['content']);
784
785 1
        $this->builder->getLogger()->debug(\sprintf('Asset minified: "%s"', $this->data['path']));
786
787 1
        return $this;
788
    }
789
790
    /**
791
     * Add hash to the file name.
792
     */
793 1
    protected function doFingerprint(): self
794
    {
795 1
        $hash = hash('md5', $this->data['content']);
796 1
        $this->data['path'] = preg_replace(
797 1
            '/\.' . $this->data['ext'] . '$/m',
798 1
            ".$hash." . $this->data['ext'],
799 1
            $this->data['path']
800 1
        );
801 1
        $this->builder->getLogger()->debug(\sprintf('Asset fingerprinted: "%s"', $this->data['path']));
802
803 1
        return $this;
804
    }
805
806
    /**
807
     * Returns local file path and updated path, or throw an exception.
808
     * If $fallback path is set, it will be used if the remote file is not found.
809
     *
810
     * Try to locate the file in:
811
     *   (1. remote file)
812
     *   1. assets
813
     *   2. themes/<theme>/assets
814
     *   3. static
815
     *   4. themes/<theme>/static
816
     *
817
     * @throws RuntimeException
818
     */
819 1
    private function locateFile(string $path, ?string $fallback = null, ?string $userAgent = null): array
820
    {
821
        // remote file
822 1
        if (Util\File::isRemote($path)) {
823
            try {
824 1
                $content = $this->getRemoteFileContent($path, $userAgent);
825 1
                $path = self::buildPathFromUrl($path);
826 1
                $cache = new Cache($this->builder, 'assets/remote');
827 1
                if (!$cache->has($path)) {
828 1
                    $cache->set($path, [
829 1
                        'content' => $content,
830 1
                        'path'    => $path,
831 1
                    ], $this->config->get('cache.assets.remote.ttl'));
832
                }
833 1
                return [
834 1
                    'file' => $cache->getContentFilePathname($path),
835 1
                    'path' => $path,
836 1
                ];
837 1
            } catch (RuntimeException $e) {
838 1
                if (empty($fallback)) {
839
                    throw new RuntimeException($e->getMessage());
840
                }
841 1
                $path = $fallback;
842
            }
843
        }
844
845
        // checks in assets/
846 1
        $file = Util::joinFile($this->config->getAssetsPath(), $path);
847 1
        if (Util\File::getFS()->exists($file)) {
848 1
            return [
849 1
                'file' => $file,
850 1
                'path' => $path,
851 1
            ];
852
        }
853
854
        // checks in each themes/<theme>/assets/
855 1
        foreach ($this->config->getTheme() ?? [] as $theme) {
856 1
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
857 1
            if (Util\File::getFS()->exists($file)) {
858 1
                return [
859 1
                    'file' => $file,
860 1
                    'path' => $path,
861 1
                ];
862
            }
863
        }
864
865
        // checks in static/
866 1
        $file = Util::joinFile($this->config->getStaticPath(), $path);
867 1
        if (Util\File::getFS()->exists($file)) {
868 1
            return [
869 1
                'file' => $file,
870 1
                'path' => $path,
871 1
            ];
872
        }
873
874
        // checks in each themes/<theme>/static/
875 1
        foreach ($this->config->getTheme() ?? [] as $theme) {
876 1
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
877 1
            if (Util\File::getFS()->exists($file)) {
878 1
                return [
879 1
                    'file' => $file,
880 1
                    'path' => $path,
881 1
                ];
882
            }
883
        }
884
885 1
        throw new RuntimeException(\sprintf('Can\'t locate file "%s".', $path));
886
    }
887
888
    /**
889
     * Try to get remote file content.
890
     * Returns file content or throw an exception.
891
     *
892
     * @throws RuntimeException
893
     */
894 1
    private function getRemoteFileContent(string $path, ?string $userAgent = null): string
895
    {
896 1
        if (!Util\File::isRemoteExists($path)) {
897 1
            throw new RuntimeException(\sprintf('Can\'t get remote file "%s".', $path));
898
        }
899 1
        if (false === $content = Util\File::fileGetContents($path, $userAgent)) {
900
            throw new RuntimeException(\sprintf('Can\'t get content of remote file "%s".', $path));
901
        }
902 1
        if (\strlen($content) <= 1) {
903
            throw new RuntimeException(\sprintf('Remote file "%s" is empty.', $path));
904
        }
905
906 1
        return $content;
907
    }
908
909
    /**
910
     * Optimizing $filepath image.
911
     * Returns the new file size.
912
     */
913 1
    private function optimize(string $filepath, string $path, int $quality): int
914
    {
915 1
        $message = \sprintf('Asset not optimized: "%s"', $path);
916 1
        $sizeBefore = filesize($filepath);
917 1
        Optimizer::create($quality)->optimize($filepath);
918 1
        $sizeAfter = filesize($filepath);
919 1
        if ($sizeAfter < $sizeBefore) {
920
            $message = \sprintf(
921
                'Asset optimized: "%s" (%s Ko -> %s Ko)',
922
                $path,
923
                ceil($sizeBefore / 1000),
924
                ceil($sizeAfter / 1000)
925
            );
926
        }
927 1
        $this->builder->getLogger()->debug($message);
928
929 1
        return $sizeAfter;
930
    }
931
932
    /**
933
     * Returns the width of an image/SVG.
934
     *
935
     * @throws RuntimeException
936
     */
937 1
    private function getWidth(): int
938
    {
939 1
        if ($this->data['type'] != 'image') {
940
            return 0;
941
        }
942 1
        if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
943 1
            return (int) $svg->width;
944
        }
945 1
        if (false === $size = $this->getImageSize()) {
946
            throw new RuntimeException(\sprintf('Not able to get width of "%s".', $this->data['path']));
947
        }
948
949 1
        return $size[0];
950
    }
951
952
    /**
953
     * Returns the height of an image/SVG.
954
     *
955
     * @throws RuntimeException
956
     */
957 1
    private function getHeight(): int
958
    {
959 1
        if ($this->data['type'] != 'image') {
960
            return 0;
961
        }
962 1
        if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
963 1
            return (int) $svg->height;
964
        }
965 1
        if (false === $size = $this->getImageSize()) {
966
            throw new RuntimeException(\sprintf('Not able to get height of "%s".', $this->data['path']));
967
        }
968
969 1
        return $size[1];
970
    }
971
972
    /**
973
     * Returns image size informations.
974
     *
975
     * @see https://www.php.net/manual/function.getimagesize.php
976
     *
977
     * @return array|false
978
     */
979 1
    private function getImageSize()
980
    {
981 1
        if (!$this->data['type'] == 'image') {
982
            return false;
983
        }
984
985
        try {
986 1
            if (false === $size = getimagesizefromstring($this->data['content'])) {
987 1
                return false;
988
            }
989
        } catch (\Exception $e) {
990
            throw new RuntimeException(\sprintf('Handling asset "%s" failed: "%s"', $this->data['path'], $e->getMessage()));
991
        }
992
993 1
        return $size;
994
    }
995
996
    /**
997
     * Builds CDN image URL.
998
     */
999
    private function buildImageCdnUrl(): string
1000
    {
1001
        return str_replace(
1002
            [
1003
                '%account%',
1004
                '%image_url%',
1005
                '%width%',
1006
                '%quality%',
1007
                '%format%',
1008
            ],
1009
            [
1010
                $this->config->get('assets.images.cdn.account') ?? '',
1011
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical') ?? true]), '/'),
1012
                $this->data['width'],
1013
                (int) $this->config->get('assets.images.quality'),
1014
                $this->data['ext'],
1015
            ],
1016
            (string) $this->config->get('assets.images.cdn.url')
1017
        );
1018
    }
1019
1020
    /**
1021
     * Checks if the asset is not missing and is typed as an image.
1022
     *
1023
     * @throws RuntimeException
1024
     */
1025 1
    private function checkImage(): void
1026
    {
1027 1
        if ($this->data['missing']) {
1028
            throw new RuntimeException(\sprintf('Not able to resize "%s": file not found.', $this->data['path']));
1029
        }
1030 1
        if ($this->data['type'] != 'image') {
1031
            throw new RuntimeException(\sprintf('Not able to resize "%s": not an image.', $this->data['path']));
1032
        }
1033
    }
1034
1035
    /**
1036
     * Remove redondant '/thumbnails/<width(xheight)>/' in the path.
1037
     */
1038 1
    private function deduplicateThumbPath(string $path): string
1039
    {
1040
        // https://regex101.com/r/1HXJmw/1
1041 1
        $pattern = '/(' . self::IMAGE_THUMB . '\/\d+(x\d+){0,1}\/)(' . self::IMAGE_THUMB . '\/\d+(x\d+){0,1}\/)(.*)/i';
1042
1043 1
        if (null === $result = preg_replace($pattern, '$1$5', $path)) {
1044
            return $path;
1045
        }
1046
1047 1
        return $result;
1048
    }
1049
}
1050