Passed
Push — refactor-fix-thumb-path ( 5e89b7 )
by Arnaud
04:32
created

Asset::deduplicateThumbPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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