Passed
Pull Request — master (#2148)
by Arnaud
11:00 queued 04:45
created

Asset::dataurl()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 2
nop 0
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 3
rs 10
c 0
b 0
f 0
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 bool */
41
    protected $fingerprinted = false;
42
43
    /** @var bool */
44
    protected $compiled = false;
45
46
    /** @var bool */
47
    protected $minified = false;
48
49
    /**
50
     * Creates an Asset from a file path, an array of files path or an URL.
51
     * Options:
52
     * [
53
     *     'fingerprint' => <bool>,
54
     *     'minify' => <bool>,
55
     *     'optimize' => <bool>,
56
     *     'filename' => <string>,
57
     *     'ignore_missing' => <bool>,
58
     *     'remote_fallback' => <string>,
59
     *     'force_slash' => <bool>
60
     * ]
61
     *
62
     * @param Builder      $builder
63
     * @param string|array $paths
64
     * @param array|null   $options
65
     *
66
     * @throws RuntimeException
67
     */
68 1
    public function __construct(Builder $builder, string|array $paths, array|null $options = null)
69
    {
70 1
        $this->builder = $builder;
71 1
        $this->config = $builder->getConfig();
72 1
        $paths = \is_array($paths) ? $paths : [$paths];
73
        // checks path(s)
74 1
        array_walk($paths, function ($path) {
75
            // must be a string
76 1
            if (!\is_string($path)) {
77
                throw new RuntimeException(\sprintf('The path of an asset must be a string ("%s" given).', \gettype($path)));
78
            }
79
            // can't be empty
80 1
            if (empty($path)) {
81
                throw new RuntimeException('The path of an asset can\'t be empty.');
82
            }
83
            // can't be relative
84 1
            if (substr($path, 0, 2) == '..') {
85
                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));
86
            }
87 1
        });
88 1
        $this->data = [
89 1
            'file'     => '',    // absolute file path
90 1
            'files'    => [],    // array of absolute files path
91 1
            'path'     => '',    // public path
92 1
            'url'      => null,  // URL if it's a remote file
93 1
            'missing'  => false, // if file not found but missing allowed: 'missing' is true
94 1
            'ext'      => '',    // file extension
95 1
            'type'     => '',    // file type (e.g.: image, audio, video, etc.)
96 1
            'subtype'  => '',    // file media type (e.g.: image/png, audio/mp3, etc.)
97 1
            'size'     => 0,     // file size (in bytes)
98 1
            'width'    => 0,     // image width (in pixels)
99 1
            'height'   => 0,     // image height (in pixels)
100 1
            'exif'     => [],    // image exif data
101 1
            'content'  => '',    // file content
102 1
        ];
103
104
        // handles options
105 1
        $fingerprint = $this->config->isEnabled('assets.fingerprint');
106 1
        $minify = $this->config->isEnabled('assets.minify');
107 1
        $optimize = $this->config->isEnabled('assets.images.optimize');
108 1
        $filename = '';
109 1
        $ignore_missing = false;
110 1
        $remote_fallback = null;
111 1
        $force_slash = true;
112 1
        extract(\is_array($options) ? $options : [], EXTR_IF_EXISTS);
113
114
        // locate file(s) and get content
115 1
        $pathsCount = \count($paths);
116 1
        for ($i = 0; $i < $pathsCount; $i++) {
117
            try {
118 1
                $this->data['missing'] = false;
119 1
                $locate = $this->locateFile($paths[$i], $remote_fallback);
120 1
                $file = $locate['file'];
121 1
                $path = $locate['path'];
122 1
                $type = Util\File::getMediaType($file)[0];
123 1
                if ($i > 0) { // bundle
124 1
                    if ($type != $this->data['type']) {
125
                        throw new RuntimeException(\sprintf('Asset bundle type error (%s != %s).', $type, $this->data['type']));
126
                    }
127
                }
128 1
                $this->data['file'] = $file;
129 1
                $this->data['files'][] = $file;
130 1
                $this->data['path'] = $path;
131 1
                $this->data['url'] = Util\File::isRemote($paths[$i]) ? $paths[$i] : null;
132 1
                $this->data['ext'] = Util\File::getExtension($file);
133 1
                $this->data['type'] = $type;
134 1
                $this->data['subtype'] = Util\File::getMediaType($file)[1];
135 1
                $this->data['size'] += filesize($file);
136 1
                $this->data['content'] .= Util\File::fileGetContents($file);
137
                // bundle default filename
138 1
                if ($pathsCount > 1 && empty($filename)) {
139 1
                    switch ($this->data['ext']) {
140 1
                        case 'scss':
141 1
                        case 'css':
142 1
                            $filename = 'styles.css';
143 1
                            break;
144 1
                        case 'js':
145 1
                            $filename = 'scripts.js';
146 1
                            break;
147
                        default:
148
                            throw new RuntimeException(\sprintf('Asset bundle supports %s files only.', '.scss, .css and .js'));
149
                    }
150
                }
151
                // apply bundle filename to path
152 1
                if (!empty($filename)) {
153 1
                    $this->data['path'] = '/' . ltrim($filename, '/');
154
                }
155
                // force root slash
156 1
                if ($force_slash) {
157 1
                    $this->data['path'] = '/' . ltrim($this->data['path'], '/');
158
                }
159 1
            } catch (RuntimeException $e) {
160 1
                if ($ignore_missing) {
161 1
                    $this->data['missing'] = true;
162 1
                    continue;
163
                }
164
                throw new RuntimeException(\sprintf('Can\'t handle asset "%s" (%s).', $paths[$i], $e->getMessage()));
165
            }
166
        }
167
168
        // missing
169 1
        if ($this->data['missing']) {
170 1
            return;
171
        }
172
173
        // cache
174 1
        $cache = new Cache($this->builder, 'assets');
175 1
        $cacheKey = $cache->createKeyFromAsset($this, $fingerprint ? ['fingerprinted'] : []);
176 1
        if (!$cache->has($cacheKey)) {
177
            // image: width, height and exif
178 1
            if ($this->data['type'] == 'image') {
179 1
                $this->data['width'] = $this->getWidth();
180 1
                $this->data['height'] = $this->getHeight();
181 1
                if ($this->data['subtype'] == 'image/jpeg') {
182 1
                    $this->data['exif'] = Util\File::readExif($this->data['file']);
183
                }
184
            }
185
            // fingerprinting
186 1
            if ($fingerprint) {
187
                $this->fingerprint();
188
            }
189 1
            $cache->set($cacheKey, $this->data);
190 1
            $this->builder->getLogger()->debug(\sprintf('Asset created: "%s"', $this->data['path']));
191
            // optimizing images files (in cache)
192 1
            if ($optimize && $this->data['type'] == 'image' && !$this->isImageInCdn()) {
193 1
                $this->optimize($cache->getContentFilePathname($this->data['path']), $this->data['path']);
194
            }
195
        }
196 1
        $this->data = $cache->get($cacheKey);
197
198
        // compiling Sass files
199 1
        $this->compile();
200
        // minifying (CSS and JavScript files)
201 1
        if ($minify) {
202 1
            $this->minify();
203
        }
204
    }
205
206
    /**
207
     * Returns path.
208
     */
209 1
    public function __toString(): string
210
    {
211 1
        $this->save();
212
213 1
        if ($this->isImageInCdn()) {
214
            return $this->buildImageCdnUrl();
215
        }
216
217 1
        if ($this->builder->getConfig()->isEnabled('canonicalurl')) {
218
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
219
        }
220
221 1
        return $this->data['path'];
222
    }
223
224
    /**
225
     * Compiles a SCSS.
226
     *
227
     * @throws RuntimeException
228
     */
229 1
    public function compile(): self
230
    {
231 1
        if ($this->compiled) {
232 1
            return $this;
233
        }
234
235 1
        if ($this->data['ext'] != 'scss') {
236 1
            return $this;
237
        }
238
239 1
        $cache = new Cache($this->builder, 'assets');
240 1
        $cacheKey = $cache->createKeyFromAsset($this, ['compiled']);
241 1
        if (!$cache->has($cacheKey)) {
242 1
            $scssPhp = new Compiler();
243
            // import paths
244 1
            $importDir = [];
245 1
            $importDir[] = Util::joinPath($this->config->getStaticPath());
246 1
            $importDir[] = Util::joinPath($this->config->getAssetsPath());
247 1
            $scssDir = (array) $this->config->get('assets.compile.import');
248 1
            $themes = $this->config->getTheme() ?? [];
249 1
            foreach ($scssDir as $dir) {
250 1
                $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir);
251 1
                $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir);
252 1
                $importDir[] = Util::joinPath(\dirname($this->data['file']), $dir);
253 1
                foreach ($themes as $theme) {
254 1
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir"));
255 1
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir"));
256
                }
257
            }
258 1
            $scssPhp->setQuietDeps(true);
259 1
            $scssPhp->setImportPaths(array_unique($importDir));
260
            // source map
261 1
            if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
262
                $importDir = [];
263
                $assetDir = (string) $this->config->get('assets.dir');
264
                $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR . $assetDir . DIRECTORY_SEPARATOR);
265
                $fileRelPath = substr($this->data['file'], $assetDirPos + 8);
266
                $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath);
267
                $importDir[] = \dirname($filePath);
268
                foreach ($scssDir as $dir) {
269
                    $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir);
270
                }
271
                $scssPhp->setImportPaths(array_unique($importDir));
272
                $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE);
273
                $scssPhp->setSourceMapOptions([
274
                    'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()),
275
                    'sourceRoot'        => '/',
276
                ]);
277
            }
278
            // output style
279 1
            $outputStyles = ['expanded', 'compressed'];
280 1
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
281 1
            if (!\in_array($outputStyle, $outputStyles)) {
282
                throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
283
            }
284 1
            $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
285
            // variables
286 1
            $variables = $this->config->get('assets.compile.variables');
287 1
            if (!empty($variables)) {
288 1
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
289 1
                $scssPhp->replaceVariables($variables);
290
            }
291
            // debug
292 1
            if ($this->builder->isDebug()) {
293 1
                $scssPhp->setQuietDeps(false);
294 1
                $this->builder->getLogger()->debug(\sprintf("SCSS compiler imported paths:\n%s", Util\Str::arrayToList(array_unique($importDir))));
295
            }
296
            // update data
297 1
            $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']);
298 1
            $this->data['ext'] = 'css';
299 1
            $this->data['type'] = 'text';
300 1
            $this->data['subtype'] = 'text/css';
301 1
            $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss();
302 1
            $this->data['size'] = \strlen($this->data['content']);
303 1
            $cache->set($cacheKey, $this->data);
304 1
            $this->compiled = true;
305 1
            $this->builder->getLogger()->debug(\sprintf('Asset compiled: "%s"', $this->data['path']));
306
        }
307 1
        $this->data = $cache->get($cacheKey);
308
309 1
        return $this;
310
    }
311
312
    /**
313
     * Minifying a CSS or a JS.
314
     *
315
     * @throws RuntimeException
316
     */
317 1
    public function minify(): self
318
    {
319
        // in debug mode, disable minify to preserve inline source map
320 1
        if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
321
            return $this;
322
        }
323
324 1
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
325
            return $this;
326
        }
327
328 1
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
329
            $this->minified = true;
330
        }
331
332 1
        if ($this->minified) {
333
            return $this;
334
        }
335
336 1
        if ($this->data['ext'] == 'scss') {
337
            $this->compile();
338
        }
339
340 1
        $cache = new Cache($this->builder, 'assets');
341 1
        $cacheKey = $cache->createKeyFromAsset($this, ['minified']);
342 1
        if (!$cache->has($cacheKey)) {
343 1
            switch ($this->data['ext']) {
344 1
                case 'css':
345 1
                    $minifier = new Minify\CSS($this->data['content']);
346 1
                    break;
347 1
                case 'js':
348 1
                    $minifier = new Minify\JS($this->data['content']);
349 1
                    break;
350
                default:
351
                    throw new RuntimeException(\sprintf('Not able to minify "%s".', $this->data['path']));
352
            }
353 1
            $this->data['content'] = $minifier->minify();
354 1
            $this->data['size'] = \strlen($this->data['content']);
355 1
            $cache->set($cacheKey, $this->data);
356 1
            $this->minified = true;
357 1
            $this->builder->getLogger()->debug(\sprintf('Asset minified: "%s"', $this->data['path']));
358
        }
359 1
        $this->data = $cache->get($cacheKey);
360
361 1
        return $this;
362
    }
363
364
    /**
365
     * Add hash to the file name.
366
     */
367 1
    public function fingerprint(): self
368
    {
369 1
        if ($this->fingerprinted) {
370
            return $this;
371
        }
372
373 1
        $cache = new Cache($this->builder, 'assets');
374 1
        $cacheKey = $cache->createKeyFromAsset($this, ['fingerprinted']);
375 1
        if (!$cache->has($cacheKey)) {
376 1
            $hash = hash('md5', $this->data['content']);
377 1
            $this->data['path'] = preg_replace(
378 1
                '/\.' . $this->data['ext'] . '$/m',
379 1
                ".$hash." . $this->data['ext'],
380 1
                $this->data['path']
381 1
            );
382 1
            $cache->set($cacheKey, $this->data);
383 1
            $this->fingerprinted = true;
384 1
            $this->builder->getLogger()->debug(\sprintf('Asset fingerprinted: "%s"', $this->data['path']));
385
        }
386 1
        $this->data = $cache->get($cacheKey);
387
388 1
        return $this;
389
    }
390
391
    /**
392
     * Optimizing $filepath image.
393
     * Returns the new file size.
394
     */
395 1
    public function optimize(string $filepath, string $path): int
396
    {
397 1
        $quality = (int) $this->config->get('assets.images.quality');
398 1
        $message = \sprintf('Asset processed: "%s"', $path);
399 1
        $sizeBefore = filesize($filepath);
400 1
        Optimizer::create($quality)->optimize($filepath);
401 1
        $sizeAfter = filesize($filepath);
402 1
        if ($sizeAfter < $sizeBefore) {
403
            $message = \sprintf(
404
                'Asset optimized: "%s" (%s Ko -> %s Ko)',
405
                $path,
406
                ceil($sizeBefore / 1000),
407
                ceil($sizeAfter / 1000)
408
            );
409
        }
410 1
        $this->builder->getLogger()->debug($message);
411
412 1
        return $sizeAfter;
413
    }
414
415
    /**
416
     * Resizes an image with a new $width.
417
     *
418
     * @throws RuntimeException
419
     */
420 1
    public function resize(int $width): self
421
    {
422 1
        if ($this->data['missing']) {
423
            throw new RuntimeException(\sprintf('Not able to resize "%s": file not found.', $this->data['path']));
424
        }
425 1
        if ($this->data['type'] != 'image') {
426
            throw new RuntimeException(\sprintf('Not able to resize "%s": not an image.', $this->data['path']));
427
        }
428 1
        if ($width >= $this->data['width']) {
429 1
            return $this;
430
        }
431
432 1
        $assetResized = clone $this;
433 1
        $assetResized->data['width'] = $width;
434
435 1
        if ($this->isImageInCdn()) {
436
            $assetResized->data['height'] = round($this->data['height'] / ($this->data['width'] / $width));
437
438
            return $assetResized; // returns asset with the new dimensions only: CDN do the rest of the job
439
        }
440
441 1
        $quality = (int) $this->config->get('assets.images.quality');
442 1
        $cache = new Cache($this->builder, 'assets');
443 1
        $cacheKey = $cache->createKeyFromAsset($assetResized, ["{$width}x", "q$quality"]);
444 1
        if (!$cache->has($cacheKey)) {
445 1
            $assetResized->data['content'] = Image::resize($assetResized, $width, $quality);
446 1
            $assetResized->data['path'] = '/' . Util::joinPath(
447 1
                (string) $this->config->get('assets.target'),
448 1
                'thumbnails',
449 1
                (string) $width,
450 1
                $assetResized->data['path']
451 1
            );
452 1
            $assetResized->data['height'] = $assetResized->getHeight();
453 1
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
454
455 1
            $cache->set($cacheKey, $assetResized->data);
456 1
            $this->builder->getLogger()->debug(\sprintf('Asset resized: "%s" (%sx)', $assetResized->data['path'], $width));
457
        }
458 1
        $assetResized->data = $cache->get($cacheKey);
459
460 1
        return $assetResized;
461
    }
462
463
    /**
464
     * Converts an image asset to $format format.
465
     *
466
     * @throws RuntimeException
467
     */
468 1
    public function convert(string $format, ?int $quality = null): self
469
    {
470 1
        if ($this->data['type'] != 'image') {
471
            throw new RuntimeException(\sprintf('Not able to convert "%s" (%s) to %s: not an image.', $this->data['path'], $this->data['type'], $format));
472
        }
473
474 1
        if ($quality === null) {
475 1
            $quality = (int) $this->config->get('assets.images.quality');
476
        }
477
478 1
        $asset = clone $this;
479 1
        $asset['ext'] = $format;
480 1
        $asset->data['subtype'] = "image/$format";
481
482 1
        if ($this->isImageInCdn()) {
483
            return $asset; // returns the asset with the new extension only: CDN do the rest of the job
484
        }
485
486 1
        $cache = new Cache($this->builder, 'assets');
487 1
        $tags = ["q$quality"];
488 1
        if ($this->data['width']) {
489 1
            array_unshift($tags, "{$this->data['width']}x");
490
        }
491 1
        $cacheKey = $cache->createKeyFromAsset($asset, $tags);
492 1
        if (!$cache->has($cacheKey)) {
493 1
            $asset->data['content'] = Image::convert($asset, $format, $quality);
494
            $asset->data['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']);
495
            $asset->data['size'] = \strlen($asset->data['content']);
496
            $cache->set($cacheKey, $asset->data);
497
            $this->builder->getLogger()->debug(\sprintf('Asset converted: "%s" (%s -> %s)', $asset->data['path'], $this->data['ext'], $format));
498
        }
499
        $asset->data = $cache->get($cacheKey);
500
501
        return $asset;
502
    }
503
504
    /**
505
     * Converts an image asset to WebP format.
506
     *
507
     * @throws RuntimeException
508
     */
509
    public function webp(?int $quality = null): self
510
    {
511
        return $this->convert('webp', $quality);
512
    }
513
514
    /**
515
     * Converts an image asset to AVIF format.
516
     *
517
     * @throws RuntimeException
518
     */
519 1
    public function avif(?int $quality = null): self
520
    {
521 1
        return $this->convert('avif', $quality);
522
    }
523
524
    /**
525
     * Implements \ArrayAccess.
526
     */
527 1
    #[\ReturnTypeWillChange]
528
    public function offsetSet($offset, $value): void
529
    {
530 1
        if (!\is_null($offset)) {
531 1
            $this->data[$offset] = $value;
532
        }
533
    }
534
535
    /**
536
     * Implements \ArrayAccess.
537
     */
538 1
    #[\ReturnTypeWillChange]
539
    public function offsetExists($offset): bool
540
    {
541 1
        return isset($this->data[$offset]);
542
    }
543
544
    /**
545
     * Implements \ArrayAccess.
546
     */
547
    #[\ReturnTypeWillChange]
548
    public function offsetUnset($offset): void
549
    {
550
        unset($this->data[$offset]);
551
    }
552
553
    /**
554
     * Implements \ArrayAccess.
555
     */
556 1
    #[\ReturnTypeWillChange]
557
    public function offsetGet($offset)
558
    {
559 1
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
560
    }
561
562
    /**
563
     * Hashing content of an asset with the specified algo, sha384 by default.
564
     * Used for SRI (Subresource Integrity).
565
     *
566
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
567
     */
568 1
    public function getIntegrity(string $algo = 'sha384'): string
569
    {
570 1
        return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
571
    }
572
573
    /**
574
     * Returns MP3 file infos.
575
     *
576
     * @see https://github.com/wapmorgan/Mp3Info
577
     */
578 1
    public function getAudio(): Mp3Info
579
    {
580 1
        if ($this->data['type'] !== 'audio') {
581
            throw new RuntimeException(\sprintf('Not able to get audio infos of "%s".', $this->data['path']));
582
        }
583
584 1
        return new Mp3Info($this->data['file']);
585
    }
586
587
    /**
588
     * Returns MP4 file infos.
589
     *
590
     * @see https://github.com/clwu88/php-read-mp4info
591
     */
592 1
    public function getVideo(): array
593
    {
594 1
        if ($this->data['type'] !== 'video') {
595
            throw new RuntimeException(\sprintf('Not able to get video infos of "%s".', $this->data['path']));
596
        }
597
598 1
        return (array) \Clwu\Mp4::getInfo($this->data['file']);
599
    }
600
601
    /**
602
     * Returns the Data URL (encoded in Base64).
603
     *
604
     * @throws RuntimeException
605
     */
606 1
    public function dataurl(): string
607
    {
608 1
        if ($this->data['type'] == 'image' && !Image::isSVG($this)) {
609 1
            return Image::getDataUrl($this, (int) $this->config->get('assets.images.quality'));
610
        }
611
612 1
        return \sprintf('data:%s;base64,%s', $this->data['subtype'], base64_encode($this->data['content']));
613
    }
614
615
    /**
616
     * Adds asset path to the list of assets to save.
617
     *
618
     * @throws RuntimeException
619
     */
620 1
    public function save(): void
621
    {
622 1
        if ($this->data['missing']) {
623 1
            return;
624
        }
625
626 1
        $cache = new Cache($this->builder, 'assets');
627 1
        if (!Util\File::getFS()->exists($cache->getContentFilePathname($this->data['path']))) {
628
            throw new RuntimeException(
629
                \sprintf('Can\'t add "%s" to assets list: file not found.', $this->data['path'])
630
            );
631
        }
632
633 1
        $this->builder->addAsset($this->data['path']);
634
    }
635
636
    /**
637
     * Is the asset an image and is it in CDN?
638
     */
639 1
    public function isImageInCdn(): bool
640
    {
641
        if (
642 1
            $this->data['type'] == 'image'
643 1
            && $this->config->isEnabled('assets.images.cdn')
644 1
            && $this->data['ext'] != 'ico'
645 1
            && (Image::isSVG($this) && $this->config->isEnabled('assets.images.cdn.svg'))
646
        ) {
647
            return true;
648
        }
649
        // handle remote image?
650 1
        if ($this->data['url'] !== null && $this->config->isEnabled('assets.images.cdn.remote')) {
651
            return true;
652
        }
653
654 1
        return false;
655
    }
656
657
    /**
658
     * Builds a relative path from a URL.
659
     * Used for remote files.
660
     */
661 1
    public static function buildPathFromUrl(string $url): string
662
    {
663 1
        $host = parse_url($url, PHP_URL_HOST);
664 1
        $path = parse_url($url, PHP_URL_PATH);
665 1
        $query = parse_url($url, PHP_URL_QUERY);
666 1
        $ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
667
668
        // Google Fonts hack
669 1
        if (Util\Str::endsWith($path, '/css') || Util\Str::endsWith($path, '/css2')) {
670 1
            $ext = 'css';
671
        }
672
673 1
        return Page::slugify(\sprintf('%s%s%s%s', $host, self::sanitize($path), $query ? "-$query" : '', $query && $ext ? ".$ext" : ''));
674
    }
675
676
    /**
677
     * Replaces some characters by '_'.
678
     */
679 1
    public static function sanitize(string $string): string
680
    {
681 1
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
682
    }
683
684
    /**
685
     * Returns local file path and updated path, or throw an exception.
686
     * Try to locate the file in:
687
     *   (1. remote file)
688
     *   1. assets
689
     *   2. themes/<theme>/assets
690
     *   3. static
691
     *   4. themes/<theme>/static
692
     *
693
     * @return array
694
     *
695
     * @throws RuntimeException
696
     *
697
     * @todo manage remote fallback
698
     */
699 1
    private function locateFile(string $path, ?string $remote_fallback = null): array
0 ignored issues
show
Unused Code introduced by
The parameter $remote_fallback is not used and could be removed. ( Ignorable by Annotation )

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

699
    private function locateFile(string $path, /** @scrutinizer ignore-unused */ ?string $remote_fallback = null): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
700
    {
701
        // remote file
702 1
        if (Util\File::isRemote($path)) {
703 1
            $url = $path;
704 1
            $path = self::buildPathFromUrl($path);
705 1
            $cache = new Cache($this->builder, 'assets/remote');
706 1
            if (!$cache->has($path)) {
707 1
                $cache->set($path, [
708 1
                    'content' => $this->getRemoteFileContent($url),
709 1
                    'path'    => $path,
710 1
                ]/*, \DateInterval::createFromDateString('7 days')*/);
711
            }
712 1
            return [
713 1
                'file' => $cache->getContentFilePathname($path),
714 1
                'path' => $path,
715 1
            ];
716
        }
717
718
        // checks in assets/
719 1
        $file = Util::joinFile($this->config->getAssetsPath(), $path);
720 1
        if (Util\File::getFS()->exists($file)) {
721 1
            return [
722 1
                'file' => $file,
723 1
                'path' => $path,
724 1
            ];
725
        }
726
727
        // checks in each themes/<theme>/assets/
728 1
        foreach ($this->config->getTheme() ?? [] as $theme) {
729 1
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
730 1
            if (Util\File::getFS()->exists($file)) {
731 1
                return [
732 1
                    'file' => $file,
733 1
                    'path' => $path,
734 1
                ];
735
            }
736
        }
737
738
        // checks in static/
739 1
        $file = Util::joinFile($this->config->getStaticTargetPath(), $path);
740 1
        if (Util\File::getFS()->exists($file)) {
741 1
            return [
742 1
                'file' => $file,
743 1
                'path' => $path,
744 1
            ];
745
        }
746
747
        // checks in each themes/<theme>/static/
748 1
        foreach ($this->config->getTheme() ?? [] as $theme) {
749 1
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
750 1
            if (Util\File::getFS()->exists($file)) {
751 1
                return [
752 1
                    'file' => $file,
753 1
                    'path' => $path,
754 1
                ];
755
            }
756
        }
757
758 1
        throw new RuntimeException(\sprintf('Can\'t locate file "%s".', $path));
759
    }
760
761
    /**
762
     * Try to get remote file content.
763
     * Returns file content or throw an exception.
764
     *
765
     * @throws RuntimeException
766
     */
767 1
    private function getRemoteFileContent(string $path): string
768
    {
769
        try {
770 1
            if (!Util\File::isRemoteExists($path)) {
771
                throw new RuntimeException(\sprintf('Remote file "%s" doesn\'t exists', $path));
772
            }
773 1
            if (false === $content = Util\File::fileGetContents($path, true)) {
774
                throw new RuntimeException(\sprintf('Can\'t get content of remote file "%s".', $path));
775
            }
776 1
            if (\strlen($content) <= 1) {
777 1
                throw new RuntimeException(\sprintf('Remote file "%s" is empty.', $path));
778
            }
779
        } catch (RuntimeException $e) {
780
            throw new RuntimeException($e->getMessage());
781
        }
782
783 1
        return $content;
784
    }
785
786
    /**
787
     * Returns the width of an image/SVG.
788
     *
789
     * @throws RuntimeException
790
     */
791 1
    private function getWidth(): int
792
    {
793 1
        if ($this->data['type'] != 'image') {
794
            return 0;
795
        }
796 1
        if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
797 1
            return (int) $svg->width;
798
        }
799 1
        if (false === $size = $this->getImageSize()) {
800
            throw new RuntimeException(\sprintf('Not able to get width of "%s".', $this->data['path']));
801
        }
802
803 1
        return $size[0];
804
    }
805
806
    /**
807
     * Returns the height of an image/SVG.
808
     *
809
     * @throws RuntimeException
810
     */
811 1
    private function getHeight(): int
812
    {
813 1
        if ($this->data['type'] != 'image') {
814
            return 0;
815
        }
816 1
        if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
817 1
            return (int) $svg->height;
818
        }
819 1
        if (false === $size = $this->getImageSize()) {
820
            throw new RuntimeException(\sprintf('Not able to get height of "%s".', $this->data['path']));
821
        }
822
823 1
        return $size[1];
824
    }
825
826
    /**
827
     * Returns image size informations.
828
     *
829
     * @see https://www.php.net/manual/function.getimagesize.php
830
     *
831
     * @return array|false
832
     */
833 1
    private function getImageSize()
834
    {
835 1
        if (!$this->data['type'] == 'image') {
836
            return false;
837
        }
838
839
        try {
840 1
            if (false === $size = getimagesizefromstring($this->data['content'])) {
841 1
                return false;
842
            }
843
        } catch (\Exception $e) {
844
            throw new RuntimeException(\sprintf('Handling asset "%s" failed: "%s"', $this->data['path'], $e->getMessage()));
845
        }
846
847 1
        return $size;
848
    }
849
850
    /**
851
     * Builds CDN image URL.
852
     */
853
    private function buildImageCdnUrl(): string
854
    {
855
        return str_replace(
856
            [
857
                '%account%',
858
                '%image_url%',
859
                '%width%',
860
                '%quality%',
861
                '%format%',
862
            ],
863
            [
864
                $this->config->get('assets.images.cdn.account') ?? '',
865
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical') ?? true]), '/'),
866
                $this->data['width'],
867
                (int) $this->config->get('assets.images.quality'),
868
                $this->data['ext'],
869
            ],
870
            (string) $this->config->get('assets.images.cdn.url')
871
        );
872
    }
873
}
874