Passed
Push — php-8.2 ( d78c68...9cb7eb )
by Arnaud
03:27
created

Asset::optimize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2.3149

Importance

Changes 0
Metric Value
cc 2
eloc 12
nc 2
nop 3
dl 0
loc 17
ccs 8
cts 14
cp 0.5714
crap 2.3149
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Cecil;
15
16
use Cecil\Asset\Image;
17
use Cecil\Builder;
18
use Cecil\Cache;
19
use Cecil\Collection\Page\Page;
20
use Cecil\Config;
21
use Cecil\Exception\ConfigException;
22
use Cecil\Exception\RuntimeException;
23
use Cecil\Url;
24
use Cecil\Util;
25
use Cecil\Util\ImageOptimizer as Optimizer;
26
use MatthiasMullie\Minify;
27
use ScssPhp\ScssPhp\Compiler;
28
use ScssPhp\ScssPhp\OutputStyle;
29
use wapmorgan\Mp3Info\Mp3Info;
30
31
/**
32
 * Asset class.
33
 *
34
 * Represents an asset (file) in the Cecil project.
35
 * Handles file locating, content reading, compiling, minifying, fingerprinting,
36
 * resizing images, and more.
37
 */
38
class Asset implements \ArrayAccess
39
{
40
    public const IMAGE_THUMB = 'thumbnails';
41
42
    /** @var Builder */
43
    protected $builder;
44
45
    /** @var Config */
46
    protected $config;
47
48
    /** @var array */
49
    protected $data = [];
50
51
    /** @var array Cache tags */
52
    protected $cacheTags = [];
53
54
    /**
55
     * Creates an Asset from a file path, an array of files path or an URL.
56
     * Options:
57
     * [
58
     *     'filename' => <string>,
59
     *     'leading_slash' => <bool>
60
     *     'ignore_missing' => <bool>,
61
     *     'fingerprint' => <bool>,
62
     *     'minify' => <bool>,
63
     *     'optimize' => <bool>,
64
     *     'fallback' => <string>,
65
     *     'useragent' => <string>,
66
     * ]
67
     *
68
     * @param Builder      $builder
69
     * @param string|array $paths
70
     * @param array|null   $options
71
     *
72
     * @throws RuntimeException
73
     */
74 1
    public function __construct(Builder $builder, string|array $paths, array|null $options = null)
75
    {
76 1
        $this->builder = $builder;
77 1
        $this->config = $builder->getConfig();
78 1
        $paths = \is_array($paths) ? $paths : [$paths];
79
        // checks path(s)
80 1
        array_walk($paths, function ($path) {
81
            // must be a string
82 1
            if (!\is_string($path)) {
83
                throw new RuntimeException(\sprintf('The path of an asset must be a string ("%s" given).', \gettype($path)));
84
            }
85
            // can't be empty
86 1
            if (empty($path)) {
87
                throw new RuntimeException('The path of an asset can\'t be empty.');
88
            }
89
            // can't be relative
90 1
            if (substr($path, 0, 2) == '..') {
91
                throw new RuntimeException(\sprintf('The path of asset "%s" is wrong: it must be directly relative to `assets` or `static` directory, or a remote URL.', $path));
92
            }
93 1
        });
94 1
        $this->data = [
95 1
            'file'     => '',    // absolute file path
96 1
            'files'    => [],    // array of absolute files path
97 1
            'missing'  => false, // if file not found but missing allowed: 'missing' is true
98 1
            '_path'    => '',    // original path
99 1
            'path'     => '',    // public path
100 1
            'url'      => null,  // URL if it's a remote file
101 1
            'ext'      => '',    // file extension
102 1
            'type'     => '',    // file type (e.g.: image, audio, video, etc.)
103 1
            'subtype'  => '',    // file media type (e.g.: image/png, audio/mp3, etc.)
104 1
            'size'     => 0,     // file size (in bytes)
105 1
            'width'    => null,  // width (in pixels)
106 1
            'height'   => null,  // height (in pixels)
107 1
            'exif'     => [],    // image exif data
108 1
            'duration' => null,  // audio or video duration
109 1
            'content'  => '',    // file content
110 1
            'hash'     => '',    // file content hash (md5)
111
        ];
112
113 1
        // handles options
114 1
        $options = array_merge(
115 1
            [
116 1
                'filename'       => '',
117 1
                'leading_slash'  => true,
118 1
                'ignore_missing' => false,
119 1
                'fingerprint'    => $this->config->isEnabled('assets.fingerprint'),
120 1
                'minify'         => $this->config->isEnabled('assets.minify'),
121 1
                'optimize'       => $this->config->isEnabled('assets.images.optimize'),
122 1
                'fallback'       => '',
123 1
                'useragent'      => (string) $this->config->get('assets.remote.useragent.default'),
124 1
            ],
125 1
            \is_array($options) ? $options : []
126
        );
127
128 1
        // cache for "locate file(s)"
129 1
        $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 1
        // locate file(s) and get content
133 1
        if (!$cache->has($locateCacheKey)) {
134 1
            $pathsCount = \count($paths);
135
            for ($i = 0; $i < $pathsCount; $i++) {
136 1
                try {
137 1
                    $this->data['missing'] = false;
138 1
                    $locate = $this->locateFile($paths[$i], $options['fallback'], $options['useragent']);
139 1
                    $file = $locate['file'];
140 1
                    $path = $locate['path'];
141 1
                    $type = Util\File::getMediaType($file)[0];
142 1
                    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 1
                    }
147 1
                    $this->data['file'] = $file;
148 1
                    $this->data['files'][] = $file;
149 1
                    $this->data['path'] = $path;
150 1
                    $this->data['url'] = Util\File::isRemote($paths[$i]) ? $paths[$i] : null;
151 1
                    $this->data['ext'] = Util\File::getExtension($file);
152 1
                    $this->data['type'] = $type;
153 1
                    $this->data['subtype'] = Util\File::getMediaType($file)[1];
154 1
                    $this->data['size'] += filesize($file) ?: 0;
155 1
                    $this->data['content'] .= Util\File::fileGetContents($file);
156
                    $this->data['hash'] = hash('md5', $this->data['content']);
157 1
                    // bundle default filename
158 1
                    $filename = $options['filename'];
159 1
                    if ($pathsCount > 1 && empty($filename)) {
160 1
                        switch ($this->data['ext']) {
161 1
                            case 'scss':
162 1
                            case 'css':
163 1
                                $filename = 'styles.css';
164 1
                                break;
165 1
                            case 'js':
166 1
                                $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 1
                    // apply bundle filename to path
173 1
                    if (!empty($filename)) {
174
                        $this->data['path'] = $filename;
175
                    }
176 1
                    // add leading slash
177 1
                    if ($options['leading_slash']) {
178
                        $this->data['path'] = '/' . ltrim($this->data['path'], '/');
179 1
                    }
180 1
                    $this->data['_path'] = $this->data['path'];
181 1
                } catch (RuntimeException $e) {
182 1
                    if ($options['ignore_missing']) {
183 1
                        $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 1
            }
192
            $cache->set($locateCacheKey, $this->data);
193 1
        }
194
        $this->data = $cache->get($locateCacheKey);
195
196 1
        // missing
197 1
        if ($this->data['missing']) {
198
            return;
199
        }
200
201 1
        // cache for "process asset"
202
        $cache = new Cache($this->builder, 'assets');
203 1
        // create cache tags from options
204
        $this->cacheTags = $options;
205 1
        // remove unnecessary cache tags
206 1
        unset($this->cacheTags['optimize'], $this->cacheTags['ignore_missing'], $this->cacheTags['fallback'], $this->cacheTags['useragent']);
207 1
        if (!\in_array($this->data['ext'], ['css', 'js', 'scss'])) {
208
            unset($this->cacheTags['minify']);
209
        }
210 1
        // optimize image?
211 1
        $optimize = false;
212 1
        if ($options['optimize'] && $this->data['type'] == 'image' && !$this->isImageInCdn()) {
213 1
            $optimize = true;
214 1
            $quality = (int) $this->config->get('assets.images.quality');
215
            $this->cacheTags['quality'] = $quality;
216 1
        }
217 1
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
218
        if (!$cache->has($cacheKey)) {
219 1
            // fingerprinting
220
            if ($options['fingerprint']) {
221
                $this->doFingerprint();
222
            }
223 1
            // compiling Sass files
224
            $this->doCompile();
225 1
            // minifying (CSS and JavaScript files)
226
            if ($options['minify']) {
227
                $this->doMinify();
228
            }
229 1
            // get width and height
230 1
            $this->data['width'] = $this->getWidth();
231 1
            $this->data['height'] = $this->getHeight();
232 1
            // get image exif
233 1
            if ($this->data['subtype'] == 'image/jpeg') {
234
                $this->data['exif'] = Util\File::readExif($this->data['file']);
235
            }
236 1
            // get duration
237 1
            if ($this->data['type'] == 'audio') {
238
                $this->data['duration'] = $this->getAudio()['duration'];
239 1
            }
240 1
            if ($this->data['type'] == 'video') {
241
                $this->data['duration'] = $this->getVideo()['duration'];
242
            }
243 1
            $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 1
        }
250
        $this->data = $cache->get($cacheKey);
251 1
    }
252
253 1
    /**
254
     * Returns path.
255
     */
256
    public function __toString(): string
257 1
    {
258
        $this->save();
259
260
        if ($this->isImageInCdn()) {
261 1
            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 1
    }
270
271 1
    /**
272 1
     * Implements \ArrayAccess.
273 1
     */
274 1
    #[\ReturnTypeWillChange]
275 1
    public function offsetSet($offset, $value): void
276 1
    {
277
        if (!\is_null($offset)) {
278 1
            $this->data[$offset] = $value;
279
        }
280 1
    }
281
282
    /**
283
     * Implements \ArrayAccess.
284
     */
285
    #[\ReturnTypeWillChange]
286 1
    public function offsetExists($offset): bool
287
    {
288 1
        return isset($this->data[$offset]);
289 1
    }
290 1
291 1
    /**
292 1
     * Implements \ArrayAccess.
293 1
     */
294
    #[\ReturnTypeWillChange]
295 1
    public function offsetUnset($offset): void
296
    {
297 1
        unset($this->data[$offset]);
298
    }
299
300
    /**
301
     * Implements \ArrayAccess.
302
     */
303 1
    #[\ReturnTypeWillChange]
304
    public function offsetGet($offset)
305 1
    {
306 1
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
307 1
    }
308 1
309 1
    /**
310 1
     * Adds asset path to the list of assets to save.
311
     *
312 1
     * @throws RuntimeException
313
     */
314 1
    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 1
            throw new RuntimeException(
323
                \sprintf('Unable to add "%s" to assets list. Please clear cache and retry.', $this->data['path'])
324 1
            );
325
        }
326
327 1
        $this->builder->addAsset($this->data['path']);
328 1
    }
329
330
    /**
331 1
     * Add hash to the file name + cache.
332 1
     */
333
    public function fingerprint(): self
334 1
    {
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 1
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
341
        }
342 1
        $this->data = $cache->get($cacheKey);
343 1
344 1
        return $this;
345 1
    }
346 1
347 1
    /**
348 1
     * Compiles a SCSS + cache.
349 1
     *
350 1
     * @throws RuntimeException
351 1
     */
352 1
    public function compile(): self
353 1
    {
354 1
        $this->cacheTags['compile'] = true;
355 1
        $cache = new Cache($this->builder, 'assets');
356 1
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
357
        if (!$cache->has($cacheKey)) {
358 1
            $this->doCompile();
359 1
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
360
        }
361 1
        $this->data = $cache->get($cacheKey);
362
363 1
        return $this;
364
    }
365
366
    /**
367
     * Minifying a CSS or a JS.
368
     */
369
    public function minify(): self
370
    {
371 1
        $this->cacheTags['minify'] = true;
372
        $cache = new Cache($this->builder, 'assets');
373 1
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
374
        if (!$cache->has($cacheKey)) {
375 1
            $this->doMinify();
376 1
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
377 1
        }
378
        $this->data = $cache->get($cacheKey);
379 1
380
        return $this;
381 1
    }
382 1
383 1
    /**
384 1
     * Returns the Data URL (encoded in Base64).
385 1
     *
386 1
     * @throws RuntimeException
387 1
     */
388 1
    public function dataurl(): string
389 1
    {
390 1
        if ($this->data['type'] == 'image' && !Image::isSVG($this)) {
391 1
            return Image::getDataUrl($this, (int) $this->config->get('assets.images.quality'));
392 1
        }
393 1
394 1
        return \sprintf('data:%s;base64,%s', $this->data['subtype'], base64_encode($this->data['content']));
395 1
    }
396
397 1
    /**
398 1
     * Hashing content of an asset with the specified algo, sha384 by default.
399
     * Used for SRI (Subresource Integrity).
400 1
     *
401
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
402 1
     */
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 1
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
448
449 1
            $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 1
454 1
        return $assetResized;
455
    }
456
457 1
    /**
458 1
     * Crops the image to the specified width and height, keeping the specified position.
459 1
     *
460
     * @throws RuntimeException
461 1
     */
462
    public function cover(int $width, int $height): self
463
    {
464
        $this->checkImage();
465 1
466 1
        $assetResized = clone $this;
467 1
        $assetResized->data['width'] = $width;
468 1
        $assetResized->data['height'] = $height;
469
470 1
        $quality = (int) $this->config->get('assets.images.quality');
471 1
472 1
        $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 1
            $padding = 20; // default padding
507
        }
508
509 1
        $assetMaskable = clone $this;
510 1
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 1
            $assetMaskable->data['content'] = Image::maskable($assetMaskable, $quality, $padding);
518
            $assetMaskable->data['path'] = '/' . Util::joinPath(
519
                (string) $this->config->get('assets.target'),
520 1
                '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 1
     *
536
     * @throws RuntimeException
537
     */
538 1
    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 1
548
        $asset = clone $this;
549 1
        $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 1
        $this->cacheTags['quality'] = $quality;
558
        if ($this->data['width']) {
559 1
            $this->cacheTags['width'] = $this->data['width'];
560
        }
561
        $cacheKey = $cache->createKeyFromAsset($asset, $this->cacheTags);
562
        if (!$cache->has($cacheKey)) {
563 1
            $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 1
    }
573
574 1
    /**
575
     * Converts an image asset to WebP format.
576
     *
577
     * @throws RuntimeException
578 1
     */
579
    public function webp(?int $quality = null): self
580 1
    {
581 1
        return $this->convert('webp', $quality);
582 1
    }
583 1
584 1
    /**
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 1
    }
593
594 1
    /**
595 1
     * Is the asset an image and is it in CDN?
596
     */
597
    public function isImageInCdn(): bool
598 1
    {
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 1
        }
607
        // handle remote image?
608 1
        if ($this->data['url'] !== null && $this->config->isEnabled('assets.images.cdn.remote')) {
609 1
            return true;
610
        }
611
612 1
        return false;
613 1
    }
614
615
    /**
616
     * Returns the width of an image/SVG or a video.
617
     *
618
     * @throws RuntimeException
619 1
     */
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 1
                    return (int) $svg->width;
626
                }
627
                if (false === $size = $this->getImageSize()) {
628 1
                    throw new RuntimeException(\sprintf('Unable to get width of "%s".', $this->data['path']));
629 1
                }
630 1
631 1
                return $size[0];
632
            case 'video':
633
                return $this->getVideo()['width'];
634
        }
635
636 1
        return null;
637
    }
638
639
    /**
640 1
     * 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 1
            case 'image':
648
                if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
649 1
                    return (int) $svg->height;
650 1
                }
651 1
                if (false === $size = $this->getImageSize()) {
652 1
                    throw new RuntimeException(\sprintf('Unable to get height of "%s".', $this->data['path']));
653
                }
654
655 1
                return $size[1];
656 1
            case 'video':
657
                return $this->getVideo()['height'];
658
        }
659 1
660
        return null;
661
    }
662
663
    /**
664
     * Returns audio file infos:
665 1
     * - duration (in seconds.microseconds)
666
     * - bitrate (in bps)
667 1
     * - 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 1
        return [
676
            'duration' => $audio->duration,
677
            'bitrate'  => $audio->bitRate,
678 1
            'channel'  => $audio->channel,
679 1
        ];
680
    }
681 1
682
    /**
683 1
     * Returns video file infos:
684 1
     * - duration (in seconds)
685 1
     * - width (in pixels)
686 1
     * - height (in pixels)
687 1
     *
688 1
     * @see https://github.com/JamesHeinrich/getID3
689 1
     */
690 1
    public function getVideo(): array
691 1
    {
692 1
        if ($this->data['type'] !== 'video') {
693 1
            throw new RuntimeException(\sprintf('Unable to get video infos of "%s".', $this->data['path']));
694 1
        }
695
696
        $video = (new \getID3())->analyze($this->data['file']);
697 1
698 1
        return [
699
            'duration' => $video['playtime_seconds'],
700 1
            '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 1
            $ext = 'css';
719 1
        }
720 1
721
        return Page::slugify(\sprintf('%s%s%s%s', $host, self::sanitize($path), $query ? "-$query" : '', $query && $ext ? ".$ext" : ''));
722
    }
723 1
724
    /**
725 1
     * Replaces some characters by '_'.
726 1
     */
727 1
    public static function sanitize(string $string): string
728 1
    {
729
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
730
    }
731 1
732 1
    /**
733 1
     * Add hash to the file name.
734
     */
735
    protected function doFingerprint(): self
736 1
    {
737 1
        $hash = hash('md5', $this->data['content']);
738 1
        $this->data['path'] = preg_replace(
739 1
            '/\.' . $this->data['ext'] . '$/m',
740 1
            ".$hash." . $this->data['ext'],
741 1
            $this->data['path']
742
        );
743 1
        $this->builder->getLogger()->debug(\sprintf('Asset fingerprinted: "%s"', $this->data['path']));
744
745 1
        return $this;
746
    }
747
748
    /**
749
     * Compiles a SCSS.
750
     *
751
     * @throws RuntimeException
752
     */
753 1
    protected function doCompile(): self
754
    {
755
        // abort if not a SCSS file
756 1
        if ($this->data['ext'] != 'scss') {
757
            return $this;
758
        }
759
        $scssPhp = new Compiler();
760 1
        // import paths
761
        $importDir = [];
762
        $importDir[] = Util::joinPath($this->config->getStaticPath());
763
        $importDir[] = Util::joinPath($this->config->getAssetsPath());
764 1
        $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 1
            $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir);
769
            $importDir[] = Util::joinPath(\dirname($this->data['file']), $dir);
770
            foreach ($themes as $theme) {
771 1
                $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir"));
772 1
                $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir"));
773 1
            }
774 1
        }
775 1
        $scssPhp->setQuietDeps(true);
776 1
        $scssPhp->setImportPaths(array_unique($importDir));
777 1
        // 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 1
            $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR . $assetDir . DIRECTORY_SEPARATOR);
782 1
            $fileRelPath = substr($this->data['file'], $assetDirPos + 8);
783
            $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath);
784 1
            $importDir[] = \dirname($filePath);
785
            foreach ($scssDir as $dir) {
786 1
                $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 1
                'sourceRoot'        => '/',
793
            ]);
794 1
        }
795 1
        // defines output style
796 1
        $outputStyles = ['expanded', 'compressed'];
797 1
        $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
798 1
        if (!\in_array($outputStyle, $outputStyles)) {
799 1
            throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
800 1
        }
801
        $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
802 1
        // 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 1
        $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss();
819
        $this->data['size'] = \strlen($this->data['content']);
820
821 1
        $this->builder->getLogger()->debug(\sprintf('Asset compiled: "%s"', $this->data['path']));
822
823 1
        return $this;
824 1
    }
825 1
826 1
    /**
827 1
     * Minifying a CSS or a JS + cache.
828 1
     *
829 1
     * @throws RuntimeException
830 1
     */
831
    protected function doMinify(): self
832 1
    {
833 1
        // compile SCSS files
834 1
        if ($this->data['ext'] == 'scss') {
835 1
            $this->doCompile();
836 1
        }
837 1
        // abort if already minified
838
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
839
            return $this;
840 1
        }
841
        // abord if not a CSS or JS file
842
        if (!\in_array($this->data['ext'], ['css', 'js'])) {
843
            return $this;
844
        }
845 1
        // in debug mode: disable minify to preserve inline source map
846 1
        if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
847 1
            return $this;
848 1
        }
849 1
        switch ($this->data['ext']) {
850 1
            case 'css':
851
                $minifier = new Minify\CSS($this->data['content']);
852
                break;
853
            case 'js':
854 1
                $minifier = new Minify\JS($this->data['content']);
855 1
                break;
856 1
            default:
857 1
                throw new RuntimeException(\sprintf('Unable to minify "%s".', $this->data['path']));
858 1
        }
859 1
        $this->data['content'] = $minifier->minify();
860 1
        $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 1
    }
866 1
867 1
    /**
868 1
     * Returns local file path and updated path, or throw an exception.
869 1
     * If $fallback path is set, it will be used if the remote file is not found.
870 1
     *
871
     * Try to locate the file in:
872
     *   (1. remote file)
873
     *   1. assets
874 1
     *   2. themes/<theme>/assets
875 1
     *   3. static
876 1
     *   4. themes/<theme>/static
877 1
     *
878 1
     * @throws RuntimeException
879 1
     */
880 1
    private function locateFile(string $path, ?string $fallback = null, ?string $userAgent = null): array
881
    {
882
        // remote file
883
        if (Util\File::isRemote($path)) {
884 1
            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 1
                }
894
                return [
895 1
                    'file' => $cache->getContentFilePathname($path),
896 1
                    'path' => $path,
897
                ];
898 1
            } catch (RuntimeException $e) {
899
                if (empty($fallback)) {
900
                    throw new RuntimeException($e->getMessage());
901 1
                }
902
                $path = $fallback;
903
            }
904
        }
905 1
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 1
            ];
913
        }
914 1
915 1
        // checks in each themes/<theme>/assets/
916 1
        foreach ($this->config->getTheme() ?? [] as $theme) {
917 1
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
918 1
            if (Util\File::getFS()->exists($file)) {
919
                return [
920
                    'file' => $file,
921
                    'path' => $path,
922
                ];
923
            }
924
        }
925
926 1
        // checks in static/
927
        $file = Util::joinFile($this->config->getStaticPath(), $path);
928 1
        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 1
        foreach ($this->config->getTheme() ?? [] as $theme) {
937
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
938 1
            if (Util\File::getFS()->exists($file)) {
939
                return [
940
                    'file' => $file,
941 1
                    'path' => $path,
942 1
                ];
943
            }
944 1
        }
945
946
        throw new RuntimeException(\sprintf('Unable to locate file "%s".', $path));
947
    }
948 1
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 1
    {
957
        if (!Util\File::isRemoteExists($path)) {
958 1
            throw new RuntimeException(\sprintf('Unable to get remote file "%s".', $path));
959
        }
960
        if (false === $content = Util\File::fileGetContents($path, $userAgent)) {
961 1
            throw new RuntimeException(\sprintf('Unable to get content of remote file "%s".', $path));
962 1
        }
963
        if (\strlen($content) <= 1) {
964 1
            throw new RuntimeException(\sprintf('Remote file "%s" is empty.', $path));
965
        }
966
967
        return $content;
968 1
    }
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 1
        Optimizer::create($quality)->optimize($filepath);
979
        $sizeAfter = filesize($filepath);
980 1
        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 1
        return $sizeAfter;
986 1
    }
987
988
    /**
989
     * Returns image size informations.
990
     *
991
     * @see https://www.php.net/manual/function.getimagesize.php
992 1
     *
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 1
            ],
1025
            [
1026 1
                $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 1
                (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 1
     * Checks if the asset is not missing and is typed as an image.
1038
     *
1039
     * @throws RuntimeException
1040 1
     */
1041
    private function checkImage(): void
1042 1
    {
1043
        if ($this->data['missing']) {
1044
            throw new RuntimeException(\sprintf('Unable to resize "%s": file not found.', $this->data['path']));
1045
        }
1046 1
        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