Passed
Push — asset ( 81d5a7...cb1413 )
by Arnaud
06:38
created

Asset::optimizeImage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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