Asset::avif()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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