Asset::getAudio()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 8
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,  // 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
     * Scales down an image to a new $width.
405
     *
406
     * @throws RuntimeException
407
     */
408
    public function resize(int $width): self
409
    {
410
        $this->checkImage();
411
412
        // if the image is already smaller than the requested width, return it
413
        if ($width >= $this->data['width']) {
414
            return $this;
415
        }
416
417
        $assetResized = clone $this;
418
        $assetResized->data['width'] = $width;
419
420
        if ($this->isImageInCdn()) {
421
            $assetResized->data['height'] = round($this->data['height'] / ($this->data['width'] / $width));
422
423
            return $assetResized; // returns asset with the new dimensions only: CDN do the rest of the job
424
        }
425
426
        $quality = (int) $this->config->get('assets.images.quality');
427
428
        $cache = new Cache($this->builder, 'assets');
429
        $assetResized->cacheTags['quality'] = $quality;
430
        $assetResized->cacheTags['width'] = $width;
431
        $cacheKey = $cache->createKeyFromAsset($assetResized, $assetResized->cacheTags);
432
        if (!$cache->has($cacheKey)) {
433
            $assetResized->data['content'] = Image::resize($assetResized, $width, $quality);
0 ignored issues
show
Bug introduced by
The call to Cecil\Asset\Image::resize() has too few arguments starting with quality. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

433
            /** @scrutinizer ignore-call */ 
434
            $assetResized->data['content'] = Image::resize($assetResized, $width, $quality);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
434
            $assetResized->data['path'] = '/' . Util::joinPath(
435
                (string) $this->config->get('assets.target'),
436
                self::IMAGE_THUMB,
437
                (string) $width,
438
                $assetResized->data['path']
439
            );
440
            $assetResized->data['path'] = $this->deduplicateThumbPath($assetResized->data['path']);
441
            $assetResized->data['height'] = $assetResized->getHeight();
442
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
443
444
            $cache->set($cacheKey, $assetResized->data, $this->config->get('cache.assets.ttl'));
445
            $this->builder->getLogger()->debug(\sprintf('Asset resized: "%s" (%sx)', $assetResized->data['path'], $width));
446
        }
447
        $assetResized->data = $cache->get($cacheKey);
448
449
        return $assetResized;
450
    }
451
452
    /**
453
     * Crops the image to the specified width and height, keeping the specified position.
454
     *
455
     * @throws RuntimeException
456
     */
457
    public function cover(int $width, int $height): self
458
    {
459
        $this->checkImage();
460
461
        $assetResized = clone $this;
462
        $assetResized->data['width'] = $width;
463
        $assetResized->data['height'] = $height;
464
465
        $quality = (int) $this->config->get('assets.images.quality');
466
467
        $cache = new Cache($this->builder, 'assets');
468
        $assetResized->cacheTags['quality'] = $quality;
469
        $assetResized->cacheTags['width'] = $width;
470
        $assetResized->cacheTags['height'] = $height;
471
        $cacheKey = $cache->createKeyFromAsset($assetResized, $assetResized->cacheTags);
472
        if (!$cache->has($cacheKey)) {
473
            $assetResized->data['content'] = Image::cover($assetResized, $width, $height, $quality);
0 ignored issues
show
Bug introduced by
The method cover() does not exist on Cecil\Asset\Image. Did you maybe mean convert()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

473
            /** @scrutinizer ignore-call */ 
474
            $assetResized->data['content'] = Image::cover($assetResized, $width, $height, $quality);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
474
            $assetResized->data['path'] = '/' . Util::joinPath(
475
                (string) $this->config->get('assets.target'),
476
                self::IMAGE_THUMB,
477
                (string) $width . 'x' . (string) $height,
478
                $assetResized->data['path']
479
            );
480
            $assetResized->data['path'] = $this->deduplicateThumbPath($assetResized->data['path']);
481
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
482
483
            $cache->set($cacheKey, $assetResized->data, $this->config->get('cache.assets.ttl'));
484
            $this->builder->getLogger()->debug(\sprintf('Asset resized: "%s" (%sx%s)', $assetResized->data['path'], $width, $height));
485
        }
486
        $assetResized->data = $cache->get($cacheKey);
487
488
        return $assetResized;
489
    }
490
491
    /**
492
     * Creates a maskable image (with a padding = 20%).
493
     *
494
     * @throws RuntimeException
495
     */
496
    public function maskable(?int $padding = null): self
497
    {
498
        $this->checkImage();
499
500
        if ($padding === null) {
501
            $padding = 20; // default padding
502
        }
503
504
        $assetMaskable = clone $this;
505
506
        $quality = (int) $this->config->get('assets.images.quality');
507
508
        $cache = new Cache($this->builder, 'assets');
509
        $assetMaskable->cacheTags['maskable'] = true;
510
        $cacheKey = $cache->createKeyFromAsset($assetMaskable, $assetMaskable->cacheTags);
511
        if (!$cache->has($cacheKey)) {
512
            $assetMaskable->data['content'] = Image::maskable($assetMaskable, $quality, $padding);
513
            $assetMaskable->data['path'] = '/' . Util::joinPath(
514
                (string) $this->config->get('assets.target'),
515
                'maskable',
516
                $assetMaskable->data['path']
517
            );
518
            $assetMaskable->data['size'] = \strlen($assetMaskable->data['content']);
519
520
            $cache->set($cacheKey, $assetMaskable->data, $this->config->get('cache.assets.ttl'));
521
            $this->builder->getLogger()->debug(\sprintf('Asset maskabled: "%s"', $assetMaskable->data['path']));
522
        }
523
        $assetMaskable->data = $cache->get($cacheKey);
524
525
        return $assetMaskable;
526
    }
527
528
    /**
529
     * Converts an image asset to $format format.
530
     *
531
     * @throws RuntimeException
532
     */
533
    public function convert(string $format, ?int $quality = null): self
534
    {
535
        if ($this->data['type'] != 'image') {
536
            throw new RuntimeException(\sprintf('Unable to convert "%s" (%s) to %s: not an image.', $this->data['path'], $this->data['type'], $format));
537
        }
538
539
        if ($quality === null) {
540
            $quality = (int) $this->config->get('assets.images.quality');
541
        }
542
543
        $asset = clone $this;
544
        $asset['ext'] = $format;
545
        $asset->data['subtype'] = "image/$format";
546
547
        if ($this->isImageInCdn()) {
548
            return $asset; // returns the asset with the new extension only: CDN do the rest of the job
549
        }
550
551
        $cache = new Cache($this->builder, 'assets');
552
        $this->cacheTags['quality'] = $quality;
553
        if ($this->data['width']) {
554
            $this->cacheTags['width'] = $this->data['width'];
555
        }
556
        $cacheKey = $cache->createKeyFromAsset($asset, $this->cacheTags);
557
        if (!$cache->has($cacheKey)) {
558
            $asset->data['content'] = Image::convert($asset, $format, $quality);
559
            $asset->data['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']);
560
            $asset->data['size'] = \strlen($asset->data['content']);
561
            $cache->set($cacheKey, $asset->data, $this->config->get('cache.assets.ttl'));
562
            $this->builder->getLogger()->debug(\sprintf('Asset converted: "%s" (%s -> %s)', $asset->data['path'], $this->data['ext'], $format));
563
        }
564
        $asset->data = $cache->get($cacheKey);
565
566
        return $asset;
567
    }
568
569
    /**
570
     * Converts an image asset to WebP format.
571
     *
572
     * @throws RuntimeException
573
     */
574
    public function webp(?int $quality = null): self
575
    {
576
        return $this->convert('webp', $quality);
577
    }
578
579
    /**
580
     * Converts an image asset to AVIF format.
581
     *
582
     * @throws RuntimeException
583
     */
584
    public function avif(?int $quality = null): self
585
    {
586
        return $this->convert('avif', $quality);
587
    }
588
589
    /**
590
     * Is the asset an image and is it in CDN?
591
     */
592
    public function isImageInCdn(): bool
593
    {
594
        if (
595
            $this->data['type'] == 'image'
596
            && $this->config->isEnabled('assets.images.cdn')
597
            && $this->data['ext'] != 'ico'
598
            && (Image::isSVG($this) && $this->config->isEnabled('assets.images.cdn.svg'))
599
        ) {
600
            return true;
601
        }
602
        // handle remote image?
603
        if ($this->data['url'] !== null && $this->config->isEnabled('assets.images.cdn.remote')) {
604
            return true;
605
        }
606
607
        return false;
608
    }
609
610
    /**
611
     * Returns the width of an image/SVG or a video.
612
     *
613
     * @throws RuntimeException
614
     */
615
    public function getWidth(): ?int
616
    {
617
        switch ($this->data['type']) {
618
            case 'image':
619
                if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
620
                    return (int) $svg->width;
621
                }
622
                if (false === $size = $this->getImageSize()) {
623
                    throw new RuntimeException(\sprintf('Unable to get width of "%s".', $this->data['path']));
624
                }
625
626
                return $size[0];
627
            case 'video':
628
                return $this->getVideo()['width'];
629
        }
630
631
        return null;
632
    }
633
634
    /**
635
     * Returns the height of an image/SVG or a video.
636
     *
637
     * @throws RuntimeException
638
     */
639
    public function getHeight(): ?int
640
    {
641
        switch ($this->data['type']) {
642
            case 'image':
643
                if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
644
                    return (int) $svg->height;
645
                }
646
                if (false === $size = $this->getImageSize()) {
647
                    throw new RuntimeException(\sprintf('Unable to get height of "%s".', $this->data['path']));
648
                }
649
650
                return $size[1];
651
            case 'video':
652
                return $this->getVideo()['height'];
653
        }
654
655
        return null;
656
    }
657
658
    /**
659
     * Returns audio file infos:
660
     * - duration (in seconds.microseconds)
661
     * - bitrate (in bps)
662
     * - channel ('stereo', 'dual_mono', 'joint_stereo' or 'mono')
663
     *
664
     * @see https://github.com/wapmorgan/Mp3Info
665
     */
666
    public function getAudio(): array
667
    {
668
        $audio = new Mp3Info($this->data['file']);
669
670
        return [
671
            'duration' => $audio->duration,
672
            'bitrate'  => $audio->bitRate,
673
            'channel'  => $audio->channel,
674
        ];
675
    }
676
677
    /**
678
     * Returns video file infos:
679
     * - duration (in seconds)
680
     * - width (in pixels)
681
     * - height (in pixels)
682
     *
683
     * @see https://github.com/JamesHeinrich/getID3
684
     */
685
    public function getVideo(): array
686
    {
687
        if ($this->data['type'] !== 'video') {
688
            throw new RuntimeException(\sprintf('Unable to get video infos of "%s".', $this->data['path']));
689
        }
690
691
        $video = (new \getID3())->analyze($this->data['file']);
692
693
        return [
694
            'duration' => $video['playtime_seconds'],
695
            'width'    => $video['video']['resolution_x'],
696
            'height'   => $video['video']['resolution_y'],
697
        ];
698
    }
699
700
    /**
701
     * Builds a relative path from a URL.
702
     * Used for remote files.
703
     */
704
    public static function buildPathFromUrl(string $url): string
705
    {
706
        $host = parse_url($url, PHP_URL_HOST);
707
        $path = parse_url($url, PHP_URL_PATH);
708
        $query = parse_url($url, PHP_URL_QUERY);
709
        $ext = pathinfo(parse_url($url, PHP_URL_PATH), \PATHINFO_EXTENSION);
710
711
        // Google Fonts hack
712
        if (Util\Str::endsWith($path, '/css') || Util\Str::endsWith($path, '/css2')) {
713
            $ext = 'css';
714
        }
715
716
        return Page::slugify(\sprintf('%s%s%s%s', $host, self::sanitize($path), $query ? "-$query" : '', $query && $ext ? ".$ext" : ''));
717
    }
718
719
    /**
720
     * Replaces some characters by '_'.
721
     */
722
    public static function sanitize(string $string): string
723
    {
724
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
725
    }
726
727
    /**
728
     * Add hash to the file name.
729
     */
730
    protected function doFingerprint(): self
731
    {
732
        $hash = hash('md5', $this->data['content']);
733
        $this->data['path'] = preg_replace(
734
            '/\.' . $this->data['ext'] . '$/m',
735
            ".$hash." . $this->data['ext'],
736
            $this->data['path']
737
        );
738
        $this->builder->getLogger()->debug(\sprintf('Asset fingerprinted: "%s"', $this->data['path']));
739
740
        return $this;
741
    }
742
743
    /**
744
     * Compiles a SCSS.
745
     *
746
     * @throws RuntimeException
747
     */
748
    protected function doCompile(): self
749
    {
750
        // abort if not a SCSS file
751
        if ($this->data['ext'] != 'scss') {
752
            return $this;
753
        }
754
        $scssPhp = new Compiler();
755
        // import paths
756
        $importDir = [];
757
        $importDir[] = Util::joinPath($this->config->getStaticPath());
758
        $importDir[] = Util::joinPath($this->config->getAssetsPath());
759
        $scssDir = (array) $this->config->get('assets.compile.import');
760
        $themes = $this->config->getTheme() ?? [];
761
        foreach ($scssDir as $dir) {
762
            $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir);
763
            $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir);
764
            $importDir[] = Util::joinPath(\dirname($this->data['file']), $dir);
765
            foreach ($themes as $theme) {
766
                $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir"));
767
                $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir"));
768
            }
769
        }
770
        $scssPhp->setQuietDeps(true);
771
        $scssPhp->setImportPaths(array_unique($importDir));
772
        // adds source map
773
        if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
774
            $importDir = [];
775
            $assetDir = (string) $this->config->get('assets.dir');
776
            $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR . $assetDir . DIRECTORY_SEPARATOR);
777
            $fileRelPath = substr($this->data['file'], $assetDirPos + 8);
778
            $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath);
779
            $importDir[] = \dirname($filePath);
780
            foreach ($scssDir as $dir) {
781
                $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir);
782
            }
783
            $scssPhp->setImportPaths(array_unique($importDir));
784
            $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE);
785
            $scssPhp->setSourceMapOptions([
786
                'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()),
787
                'sourceRoot'        => '/',
788
            ]);
789
        }
790
        // defines output style
791
        $outputStyles = ['expanded', 'compressed'];
792
        $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
793
        if (!\in_array($outputStyle, $outputStyles)) {
794
            throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
795
        }
796
        $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
797
        // set variables
798
        $variables = $this->config->get('assets.compile.variables');
799
        if (!empty($variables)) {
800
            $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
801
            $scssPhp->replaceVariables($variables);
802
        }
803
        // debug
804
        if ($this->builder->isDebug()) {
805
            $scssPhp->setQuietDeps(false);
806
            $this->builder->getLogger()->debug(\sprintf("SCSS compiler imported paths:\n%s", Util\Str::arrayToList(array_unique($importDir))));
807
        }
808
        // update data
809
        $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']);
810
        $this->data['ext'] = 'css';
811
        $this->data['type'] = 'text';
812
        $this->data['subtype'] = 'text/css';
813
        $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss();
814
        $this->data['size'] = \strlen($this->data['content']);
815
816
        $this->builder->getLogger()->debug(\sprintf('Asset compiled: "%s"', $this->data['path']));
817
818
        return $this;
819
    }
820
821
    /**
822
     * Minifying a CSS or a JS + cache.
823
     *
824
     * @throws RuntimeException
825
     */
826
    protected function doMinify(): self
827
    {
828
        // compile SCSS files
829
        if ($this->data['ext'] == 'scss') {
830
            $this->doCompile();
831
        }
832
        // abort if already minified
833
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
834
            return $this;
835
        }
836
        // abord if not a CSS or JS file
837
        if (!\in_array($this->data['ext'], ['css', 'js'])) {
838
            return $this;
839
        }
840
        // in debug mode: disable minify to preserve inline source map
841
        if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
842
            return $this;
843
        }
844
        switch ($this->data['ext']) {
845
            case 'css':
846
                $minifier = new Minify\CSS($this->data['content']);
847
                break;
848
            case 'js':
849
                $minifier = new Minify\JS($this->data['content']);
850
                break;
851
            default:
852
                throw new RuntimeException(\sprintf('Unable to minify "%s".', $this->data['path']));
853
        }
854
        $this->data['content'] = $minifier->minify();
855
        $this->data['size'] = \strlen($this->data['content']);
856
857
        $this->builder->getLogger()->debug(\sprintf('Asset minified: "%s"', $this->data['path']));
858
859
        return $this;
860
    }
861
862
    /**
863
     * Returns local file path and updated path, or throw an exception.
864
     * If $fallback path is set, it will be used if the remote file is not found.
865
     *
866
     * Try to locate the file in:
867
     *   (1. remote file)
868
     *   1. assets
869
     *   2. themes/<theme>/assets
870
     *   3. static
871
     *   4. themes/<theme>/static
872
     *
873
     * @throws RuntimeException
874
     */
875
    private function locateFile(string $path, ?string $fallback = null, ?string $userAgent = null): array
876
    {
877
        // remote file
878
        if (Util\File::isRemote($path)) {
879
            try {
880
                $url = $path;
881
                $path = self::buildPathFromUrl($url);
882
                $cache = new Cache($this->builder, 'assets/remote');
883
                if (!$cache->has($path)) {
884
                    $content = $this->getRemoteFileContent($url, $userAgent);
885
                    $cache->set($path, [
886
                        'content' => $content,
887
                        'path'    => $path,
888
                    ], $this->config->get('cache.assets.remote.ttl'));
889
                }
890
                return [
891
                    'file' => $cache->getContentFilePathname($path),
892
                    'path' => $path,
893
                ];
894
            } catch (RuntimeException $e) {
895
                if (empty($fallback)) {
896
                    throw new RuntimeException($e->getMessage());
897
                }
898
                $path = $fallback;
899
            }
900
        }
901
902
        // checks in assets/
903
        $file = Util::joinFile($this->config->getAssetsPath(), $path);
904
        if (Util\File::getFS()->exists($file)) {
905
            return [
906
                'file' => $file,
907
                'path' => $path,
908
            ];
909
        }
910
911
        // checks in each themes/<theme>/assets/
912
        foreach ($this->config->getTheme() ?? [] as $theme) {
913
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
914
            if (Util\File::getFS()->exists($file)) {
915
                return [
916
                    'file' => $file,
917
                    'path' => $path,
918
                ];
919
            }
920
        }
921
922
        // checks in static/
923
        $file = Util::joinFile($this->config->getStaticPath(), $path);
924
        if (Util\File::getFS()->exists($file)) {
925
            return [
926
                'file' => $file,
927
                'path' => $path,
928
            ];
929
        }
930
931
        // checks in each themes/<theme>/static/
932
        foreach ($this->config->getTheme() ?? [] as $theme) {
933
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
934
            if (Util\File::getFS()->exists($file)) {
935
                return [
936
                    'file' => $file,
937
                    'path' => $path,
938
                ];
939
            }
940
        }
941
942
        throw new RuntimeException(\sprintf('Unable to locate file "%s".', $path));
943
    }
944
945
    /**
946
     * Try to get remote file content.
947
     * Returns file content or throw an exception.
948
     *
949
     * @throws RuntimeException
950
     */
951
    private function getRemoteFileContent(string $path, ?string $userAgent = null): string
952
    {
953
        if (!Util\File::isRemoteExists($path)) {
954
            throw new RuntimeException(\sprintf('Unable to get remote file "%s".', $path));
955
        }
956
        if (false === $content = Util\File::fileGetContents($path, $userAgent)) {
957
            throw new RuntimeException(\sprintf('Unable to get content of remote file "%s".', $path));
958
        }
959
        if (\strlen($content) <= 1) {
960
            throw new RuntimeException(\sprintf('Remote file "%s" is empty.', $path));
961
        }
962
963
        return $content;
964
    }
965
966
    /**
967
     * Optimizing $filepath image.
968
     * Returns the new file size.
969
     */
970
    private function optimizeImage(string $filepath, string $path, int $quality): int
971
    {
972
        $message = \sprintf('Asset not optimized: "%s"', $path);
973
        $sizeBefore = filesize($filepath);
974
        Optimizer::create($quality)->optimize($filepath);
975
        $sizeAfter = filesize($filepath);
976
        if ($sizeAfter < $sizeBefore) {
977
            $message = \sprintf('Asset optimized: "%s" (%s Ko -> %s Ko)', $path, ceil($sizeBefore / 1000), ceil($sizeAfter / 1000));
978
        }
979
        $this->builder->getLogger()->debug($message);
980
981
        return $sizeAfter;
982
    }
983
984
    /**
985
     * Returns image size informations.
986
     *
987
     * @see https://www.php.net/manual/function.getimagesize.php
988
     *
989
     * @throws RuntimeException
990
     */
991
    private function getImageSize(): array|false
992
    {
993
        if (!$this->data['type'] == 'image') {
994
            return false;
995
        }
996
997
        try {
998
            if (false === $size = getimagesizefromstring($this->data['content'])) {
999
                return false;
1000
            }
1001
        } catch (\Exception $e) {
1002
            throw new RuntimeException(\sprintf('Handling asset "%s" failed: "%s".', $this->data['path'], $e->getMessage()));
1003
        }
1004
1005
        return $size;
1006
    }
1007
1008
    /**
1009
     * Builds CDN image URL.
1010
     */
1011
    private function buildImageCdnUrl(): string
1012
    {
1013
        return str_replace(
1014
            [
1015
                '%account%',
1016
                '%image_url%',
1017
                '%width%',
1018
                '%quality%',
1019
                '%format%',
1020
            ],
1021
            [
1022
                $this->config->get('assets.images.cdn.account') ?? '',
1023
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical') ?? true]), '/'),
1024
                $this->data['width'],
1025
                (int) $this->config->get('assets.images.quality'),
1026
                $this->data['ext'],
1027
            ],
1028
            (string) $this->config->get('assets.images.cdn.url')
1029
        );
1030
    }
1031
1032
    /**
1033
     * Checks if the asset is not missing and is typed as an image.
1034
     *
1035
     * @throws RuntimeException
1036
     */
1037
    private function checkImage(): void
1038
    {
1039
        if ($this->data['missing']) {
1040
            throw new RuntimeException(\sprintf('Unable to resize "%s": file not found.', $this->data['path']));
1041
        }
1042
        if ($this->data['type'] != 'image') {
1043
            throw new RuntimeException(\sprintf('Unable to resize "%s": not an image.', $this->data['path']));
1044
        }
1045
    }
1046
1047
    /**
1048
     * Remove redondant '/thumbnails/<width(xheight)>/' in the path.
1049
     */
1050
    private function deduplicateThumbPath(string $path): string
1051
    {
1052
        // https://regex101.com/r/1HXJmw/1
1053
        $pattern = '/(' . self::IMAGE_THUMB . '\/\d+(x\d+){0,1}\/)(' . self::IMAGE_THUMB . '\/\d+(x\d+){0,1}\/)(.*)/i';
1054
1055
        if (null === $result = preg_replace($pattern, '$1$5', $path)) {
1056
            return $path;
1057
        }
1058
1059
        return $result;
1060
    }
1061
}
1062