Passed
Pull Request — master (#2277)
by Arnaud
07:35 queued 03:05
created

Asset::__construct()   F

Complexity

Conditions 34
Paths 1438

Size

Total Lines 174
Code Lines 117

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 113
CRAP Score 34.3337

Importance

Changes 0
Metric Value
cc 34
eloc 117
nc 1438
nop 3
dl 0
loc 174
ccs 113
cts 121
cp 0.9339
crap 34.3337
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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