Passed
Push — master ( 46ae56...237bda )
by
unknown
07:12
created

Asset::compile()   C

Complexity

Conditions 12
Paths 12

Size

Total Lines 79
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 44
CRAP Score 14.3653

Importance

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