Passed
Push — lqip ( ff94c1 )
by Arnaud
04:49
created

Asset::getAudio()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
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\Util;
23
use Intervention\Image\ImageManagerStatic as ImageManager;
24
use MatthiasMullie\Minify;
25
use ScssPhp\ScssPhp\Compiler;
26
use wapmorgan\Mp3Info\Mp3Info;
27
28
class Asset implements \ArrayAccess
29
{
30
    /** @var Builder */
31
    protected $builder;
32
33
    /** @var Config */
34
    protected $config;
35
36
    /** @var array */
37
    protected $data = [];
38
39
    /** @var bool */
40
    protected $fingerprinted = false;
41
42
    /** @var bool */
43
    protected $compiled = false;
44
45
    /** @var bool */
46
    protected $minified = false;
47
48
    /** @var bool */
49
    protected $optimize = false;
50
51
    /** @var bool */
52
    protected $ignore_missing = false;
53
54
    /**
55
     * Creates an Asset from a file path, an array of files path or an URL.
56
     *
57
     * @param Builder      $builder
58
     * @param string|array $paths
59
     * @param array|null   $options e.g.: ['fingerprint' => true, 'minify' => true, 'filename' => '', 'ignore_missing' => false]
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
        array_walk($paths, function ($path) {
69
            if (!\is_string($path)) {
70
                throw new RuntimeException(sprintf('The path of an asset must be a string ("%s" given).', \gettype($path)));
71
            }
72
            if (empty($path)) {
73
                throw new RuntimeException('The path of an asset can\'t be empty.');
74
            }
75
            if (substr($path, 0, 2) == '..') {
76
                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));
77
            }
78
        });
79
        $this->data = [
80
            'file'           => '',    // absolute file path
81
            'files'          => [],    // array of files path (if bundle)
82
            'filename'       => '',    // filename
83
            'path_source'    => '',    // public path to the file, before transformations
84
            'path'           => '',    // public path to the file, after transformations
85
            'url'            => null,  // URL of a remote image
86
            'missing'        => false, // if file not found, but missing ollowed 'missing' is true
87
            'ext'            => '',    // file extension
88
            'type'           => '',    // file type (e.g.: image, audio, video, etc.)
89
            'subtype'        => '',    // file media type (e.g.: image/png, audio/mp3, etc.)
90
            'size'           => 0,     // file size (in bytes)
91
            'content_source' => '',    // file content, before transformations
92
            'content'        => '',    // file content, after transformations
93
            'width'          => 0,     // width (in pixels) in case of an image
94
            'height'         => 0,     // height (in pixels) in case of an image
95
            'exif'           => [],    // exif data
96
        ];
97
98
        // handles options
99
        $fingerprint = (bool) $this->config->get('assets.fingerprint.enabled');
100
        $minify = (bool) $this->config->get('assets.minify.enabled');
101
        $optimize = (bool) $this->config->get('assets.images.optimize.enabled');
102
        $filename = '';
103
        $ignore_missing = false;
104
        $remote_fallback = null;
105
        $force_slash = true;
106
        extract(\is_array($options) ? $options : [], EXTR_IF_EXISTS);
107
        $this->ignore_missing = $ignore_missing;
108
109
        // fill data array with file(s) informations
110
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
111
        $cacheKey = sprintf('%s__%s', $filename ?: implode('_', $paths), $this->builder->getVersion());
112
        if (!$cache->has($cacheKey)) {
113
            $pathsCount = \count($paths);
114
            $file = [];
115
            for ($i = 0; $i < $pathsCount; $i++) {
116
                // loads file(s)
117
                $file[$i] = $this->loadFile($paths[$i], $ignore_missing, $remote_fallback, $force_slash);
118
                // bundle: same type only
119
                if ($i > 0) {
120
                    if ($file[$i]['type'] != $file[$i - 1]['type']) {
121
                        throw new RuntimeException(sprintf('Asset bundle type error (%s != %s).', $file[$i]['type'], $file[$i - 1]['type']));
122
                    }
123
                }
124
                // missing allowed = empty path
125
                if ($file[$i]['missing']) {
126
                    $this->data['missing'] = true;
127
                    $this->data['path'] = $file[$i]['path'];
128
129
                    continue;
130
                }
131
                // set data
132
                $this->data['size'] += $file[$i]['size'];
133
                $this->data['content_source'] .= $file[$i]['content'];
134
                $this->data['content'] .= $file[$i]['content'];
135
                if ($i == 0) {
136
                    $this->data['file'] = $file[$i]['filepath'];
137
                    $this->data['filename'] = $file[$i]['path'];
138
                    $this->data['path_source'] = $file[$i]['path'];
139
                    $this->data['path'] = $file[$i]['path'];
140
                    $this->data['url'] = $file[$i]['url'];
141
                    $this->data['ext'] = $file[$i]['ext'];
142
                    $this->data['type'] = $file[$i]['type'];
143
                    $this->data['subtype'] = $file[$i]['subtype'];
144
                    if ($this->data['type'] == 'image') {
145
                        $this->data['width'] = $this->getWidth();
146
                        $this->data['height'] = $this->getHeight();
147
                        if ($this->data['subtype'] == 'jpeg') {
148
                            $this->data['exif'] = Util\File::readExif($file[$i]['filepath']);
149
                        }
150
                    }
151
                    // bundle: default filename
152
                    if ($pathsCount > 1 && empty($filename)) {
153
                        switch ($this->data['ext']) {
154
                            case 'scss':
155
                            case 'css':
156
                                $filename = '/styles.css';
157
                                break;
158
                            case 'js':
159
                                $filename = '/scripts.js';
160
                                break;
161
                            default:
162
                                throw new RuntimeException(sprintf('Asset bundle supports %s files only.', '.scss, .css and .js'));
163
                        }
164
                    }
165
                    // bundle: filename and path
166
                    if (!empty($filename)) {
167
                        $this->data['filename'] = $filename;
168
                        $this->data['path'] = '/' . ltrim($filename, '/');
169
                    }
170
                }
171
                // bundle: files path
172
                $this->data['files'][] = $file[$i]['filepath'];
173
            }
174
            $cache->set($cacheKey, $this->data);
175
        }
176
        $this->data = $cache->get($cacheKey);
177
178
        // fingerprinting
179
        if ($fingerprint) {
180
            $this->fingerprint();
181
        }
182
        // compiling (Sass files)
183
        if ((bool) $this->config->get('assets.compile.enabled')) {
184
            $this->compile();
185
        }
186
        // minifying (CSS and JavScript files)
187
        if ($minify) {
188
            $this->minify();
189
        }
190
        // optimizing (images files)
191
        if ($optimize) {
192
            $this->optimize = true;
193
        }
194
    }
195
196
    /**
197
     * Returns path.
198
     *
199
     * @throws RuntimeException
200
     */
201
    public function __toString(): string
202
    {
203
        try {
204
            $this->save();
205
        } catch (RuntimeException $e) {
206
            $this->builder->getLogger()->error($e->getMessage());
207
        }
208
209
        if ($this->isImageInCdn()) {
210
            return $this->buildImageCdnUrl();
211
        }
212
213
        if ($this->builder->getConfig()->get('canonicalurl')) {
214
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
215
        }
216
217
        return $this->data['path'];
218
    }
219
220
    /**
221
     * Fingerprints a file.
222
     */
223
    public function fingerprint(): self
224
    {
225
        if ($this->fingerprinted) {
226
            return $this;
227
        }
228
229
        $fingerprint = hash('md5', $this->data['content_source']);
230
        $this->data['path'] = preg_replace(
231
            '/\.' . $this->data['ext'] . '$/m',
232
            ".$fingerprint." . $this->data['ext'],
233
            $this->data['path']
234
        );
235
236
        $this->fingerprinted = true;
237
238
        return $this;
239
    }
240
241
    /**
242
     * Compiles a SCSS.
243
     *
244
     * @throws RuntimeException
245
     */
246
    public function compile(): self
247
    {
248
        if ($this->compiled) {
249
            return $this;
250
        }
251
252
        if ($this->data['ext'] != 'scss') {
253
            return $this;
254
        }
255
256
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
257
        $cacheKey = $cache->createKeyFromAsset($this, ['compiled']);
258
        if (!$cache->has($cacheKey)) {
259
            $scssPhp = new Compiler();
260
            $importDir = [];
261
            $importDir[] = Util::joinPath($this->config->getStaticPath());
262
            $importDir[] = Util::joinPath($this->config->getAssetsPath());
263
            $scssDir = $this->config->get('assets.compile.import') ?? [];
264
            $themes = $this->config->getTheme() ?? [];
265
            foreach ($scssDir as $dir) {
266
                $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir);
267
                $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir);
268
                $importDir[] = Util::joinPath(\dirname($this->data['file']), $dir);
269
                foreach ($themes as $theme) {
270
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir"));
271
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir"));
272
                }
273
            }
274
            $scssPhp->setImportPaths(array_unique($importDir));
275
            // source map
276
            if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) {
277
                $importDir = [];
278
                $assetDir = (string) $this->config->get('assets.dir');
279
                $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR . $assetDir . DIRECTORY_SEPARATOR);
280
                $fileRelPath = substr($this->data['file'], $assetDirPos + 8);
281
                $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath);
282
                $importDir[] = \dirname($filePath);
283
                foreach ($scssDir as $dir) {
284
                    $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir);
285
                }
286
                $scssPhp->setImportPaths(array_unique($importDir));
287
                $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE);
288
                $scssPhp->setSourceMapOptions([
289
                    'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()),
290
                    'sourceRoot'        => '/',
291
                ]);
292
            }
293
            // output style
294
            $outputStyles = ['expanded', 'compressed'];
295
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
296
            if (!\in_array($outputStyle, $outputStyles)) {
297
                throw new ConfigException(sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
298
            }
299
            $scssPhp->setOutputStyle($outputStyle);
300
            // variables
301
            $variables = $this->config->get('assets.compile.variables') ?? [];
302
            if (!empty($variables)) {
303
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
304
                $scssPhp->replaceVariables($variables);
305
            }
306
            // update data
307
            $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']);
308
            $this->data['ext'] = 'css';
309
            $this->data['type'] = 'text';
310
            $this->data['subtype'] = 'text/css';
311
            $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss();
312
            $this->data['size'] = \strlen($this->data['content']);
313
            $this->compiled = true;
314
            $cache->set($cacheKey, $this->data);
315
        }
316
        $this->data = $cache->get($cacheKey);
317
318
        return $this;
319
    }
320
321
    /**
322
     * Minifying a CSS or a JS.
323
     *
324
     * @throws RuntimeException
325
     */
326
    public function minify(): self
327
    {
328
        // disable minify to preserve inline source map
329
        if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) {
330
            return $this;
331
        }
332
333
        if ($this->minified) {
334
            return $this;
335
        }
336
337
        if ($this->data['ext'] == 'scss') {
338
            $this->compile();
339
        }
340
341
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
342
            return $this;
343
        }
344
345
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
346
            $this->minified;
347
348
            return $this;
349
        }
350
351
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
352
        $cacheKey = $cache->createKeyFromAsset($this, ['minified']);
353
        if (!$cache->has($cacheKey)) {
354
            switch ($this->data['ext']) {
355
                case 'css':
356
                    $minifier = new Minify\CSS($this->data['content']);
357
                    break;
358
                case 'js':
359
                    $minifier = new Minify\JS($this->data['content']);
360
                    break;
361
                default:
362
                    throw new RuntimeException(sprintf('Not able to minify "%s".', $this->data['path']));
363
            }
364
            $this->data['path'] = preg_replace(
365
                '/\.' . $this->data['ext'] . '$/m',
366
                '.min.' . $this->data['ext'],
367
                $this->data['path']
368
            );
369
            $this->data['content'] = $minifier->minify();
370
            $this->data['size'] = \strlen($this->data['content']);
371
            $this->minified = true;
372
            $cache->set($cacheKey, $this->data);
373
        }
374
        $this->data = $cache->get($cacheKey);
375
376
        return $this;
377
    }
378
379
    /**
380
     * Optimizing an image.
381
     */
382
    public function optimize(string $filepath): self
383
    {
384
        if ($this->data['type'] != 'image') {
385
            return $this;
386
        }
387
388
        $quality = $this->config->get('assets.images.quality') ?? 75;
389
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
390
        $tags = ["q$quality", 'optimized'];
391
        if ($this->data['width']) {
392
            array_unshift($tags, "{$this->data['width']}x");
393
        }
394
        $cacheKey = $cache->createKeyFromAsset($this, $tags);
395
        if (!$cache->has($cacheKey)) {
396
            $message = $filepath;
397
            $sizeBefore = filesize($filepath);
398
            Optimizer::create($quality)->optimize($filepath);
399
            $sizeAfter = filesize($filepath);
400
            if ($sizeAfter < $sizeBefore) {
401
                $message = sprintf(
402
                    '%s (%s Ko -> %s Ko)',
403
                    $message,
404
                    ceil($sizeBefore / 1000),
405
                    ceil($sizeAfter / 1000)
406
                );
407
            }
408
            $this->data['content'] = Util\File::fileGetContents($filepath);
409
            $this->data['size'] = $sizeAfter;
410
            $cache->set($cacheKey, $this->data);
411
            $this->builder->getLogger()->debug(sprintf('Asset "%s" optimized', $message));
412
        }
413
        $this->data = $cache->get($cacheKey, $this->data);
414
415
        return $this;
416
    }
417
418
    /**
419
     * Resizes an image with a new $width.
420
     *
421
     * @throws RuntimeException
422
     */
423
    public function resize(int $width, ?int $quality = null): self
424
    {
425
        if ($this->data['missing']) {
426
            throw new RuntimeException(sprintf('Not able to resize "%s": file not found.', $this->data['path']));
427
        }
428
        if ($this->data['type'] != 'image') {
429
            throw new RuntimeException(sprintf('Not able to resize "%s": not an image.', $this->data['path']));
430
        }
431
        if ($width >= $this->data['width'] && $quality === null) {
432
            return $this;
433
        }
434
435
        $assetResized = clone $this;
436
        $assetResized->data['width'] = $width;
437
438
        if ($this->isImageInCdn()) {
439
            return $assetResized; // returns the asset with the new width only: CDN do the rest of the job
440
        }
441
442
        $quality = $quality ?? $this->config->get('assets.images.quality');
443
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
444
        $cacheKey = $cache->createKeyFromAsset($assetResized, ["{$width}x", "q$quality"]);
445
        if (!$cache->has($cacheKey)) {
446
            if ($assetResized->data['type'] !== 'image') {
447
                throw new RuntimeException(sprintf('Not able to resize "%s".', $assetResized->data['path']));
448
            }
449
            if (!\extension_loaded('gd')) {
450
                throw new RuntimeException('GD extension is required to use images resize.');
451
            }
452
453
            try {
454
                $img = ImageManager::make($assetResized->data['content_source'])->encode($assetResized->data['ext']);
455
                $img->resize($width, null, function (\Intervention\Image\Constraint $constraint) {
456
                    $constraint->aspectRatio();
457
                    $constraint->upsize();
458
                });
459
            } catch (\Exception $e) {
460
                throw new RuntimeException(sprintf('Not able to resize image "%s": %s', $assetResized->data['path'], $e->getMessage()));
461
            }
462
            $assetResized->data['path'] = '/' . Util::joinPath(
463
                (string) $this->config->get('assets.target'),
464
                (string) $this->config->get('assets.images.resize.dir'),
465
                (string) $width,
466
                (string) $quality,
467
                $assetResized->data['path']
468
            );
469
470
            try {
471
                if ($assetResized->data['subtype'] == 'image/jpeg') {
472
                    $img->interlace();
473
                }
474
                $assetResized->data['content'] = (string) $img->encode($assetResized->data['ext'], $quality);
475
                $img->destroy();
476
                $assetResized->data['height'] = $assetResized->getHeight();
477
                $assetResized->data['size'] = \strlen($assetResized->data['content']);
478
            } catch (\Exception $e) {
479
                throw new RuntimeException(sprintf('Not able to encode image "%s": %s', $assetResized->data['path'], $e->getMessage()));
480
            }
481
482
            $cache->set($cacheKey, $assetResized->data);
483
        }
484
        $assetResized->data = $cache->get($cacheKey);
485
486
        return $assetResized;
487
    }
488
489
    /**
490
     * Converts an image asset to WebP format.
491
     *
492
     * @throws RuntimeException
493
     */
494
    public function webp(?int $quality = null): self
495
    {
496
        if ($this->data['type'] !== 'image') {
497
            throw new RuntimeException(sprintf('can\'t convert "%s" (%s) to WebP: it\'s not an image file.', $this->data['path'], $this->data['type']));
498
        }
499
500
        if ($quality === null) {
501
            $quality = (int) $this->config->get('assets.images.quality') ?? 75;
502
        }
503
504
        $assetWebp = clone $this;
505
        $format = 'webp';
506
        $assetWebp['ext'] = $format;
507
508
        if ($this->isImageInCdn()) {
509
            return $assetWebp; // returns the asset with the new extension ('webp') only: CDN do the rest of the job
510
        }
511
512
        $img = ImageManager::make($assetWebp['content']);
513
        $assetWebp['content'] = (string) $img->encode($format, $quality);
514
        $img->destroy();
515
        $assetWebp['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']);
516
        $assetWebp['subtype'] = "image/$format";
517
        $assetWebp['size'] = \strlen($assetWebp['content']);
0 ignored issues
show
Bug introduced by
It seems like $assetWebp['content'] can also be of type null; however, parameter $string of strlen() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

517
        $assetWebp['size'] = \strlen(/** @scrutinizer ignore-type */ $assetWebp['content']);
Loading history...
518
519
        return $assetWebp;
520
    }
521
522
    /**
523
     * Implements \ArrayAccess.
524
     */
525
    #[\ReturnTypeWillChange]
526
    public function offsetSet($offset, $value): void
527
    {
528
        if (!\is_null($offset)) {
529
            $this->data[$offset] = $value;
530
        }
531
    }
532
533
    /**
534
     * Implements \ArrayAccess.
535
     */
536
    #[\ReturnTypeWillChange]
537
    public function offsetExists($offset): bool
538
    {
539
        return isset($this->data[$offset]);
540
    }
541
542
    /**
543
     * Implements \ArrayAccess.
544
     */
545
    #[\ReturnTypeWillChange]
546
    public function offsetUnset($offset): void
547
    {
548
        unset($this->data[$offset]);
549
    }
550
551
    /**
552
     * Implements \ArrayAccess.
553
     */
554
    #[\ReturnTypeWillChange]
555
    public function offsetGet($offset)
556
    {
557
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
558
    }
559
560
    /**
561
     * Hashing content of an asset with the specified algo, sha384 by default.
562
     * Used for SRI (Subresource Integrity).
563
     *
564
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
565
     */
566
    public function getIntegrity(string $algo = 'sha384'): string
567
    {
568
        return sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
569
    }
570
571
    /**
572
     * Returns MP3 file infos.
573
     *
574
     * @see https://github.com/wapmorgan/Mp3Info
575
     */
576
    public function getAudio(): Mp3Info
577
    {
578
        if ($this->data['type'] !== 'audio') {
579
            throw new RuntimeException(sprintf('Not able to get audio infos of "%s".', $this->data['path']));
580
        }
581
582
        return new Mp3Info($this->data['file']);
583
    }
584
585
    /**
586
     * Returns MP4 file infos.
587
     *
588
     * @see https://github.com/clwu88/php-read-mp4info
589
     */
590
    public function getVideo(): array
591
    {
592
        if ($this->data['type'] !== 'video') {
593
            throw new RuntimeException(sprintf('Not able to get video infos of "%s".', $this->data['path']));
594
        }
595
596
        return \Clwu\Mp4::getInfo($this->data['file']);
597
    }
598
599
    /**
600
     * Returns the data URL (encoded in Base64).
601
     *
602
     * @throws RuntimeException
603
     */
604
    public function dataurl(): string
605
    {
606
        if ($this->data['type'] == 'image' && !$this->isSVG()) {
607
            return (string) ImageManager::make($this->data['content'])->encode('data-url', $this->config->get('assets.images.quality'));
608
        }
609
610
        return sprintf('data:%s;base64,%s', $this->data['subtype'], base64_encode($this->data['content']));
611
    }
612
613
    /**
614
     * Saves file.
615
     * Note: a file from `static/` with the same name will NOT be overridden.
616
     *
617
     * @throws RuntimeException
618
     */
619
    public function save(): void
620
    {
621
        $filepath = Util::joinFile($this->config->getOutputPath(), $this->data['path']);
622
        if (!$this->builder->getBuildOptions()['dry-run'] && !Util\File::getFS()->exists($filepath)) {
623
            try {
624
                Util\File::getFS()->dumpFile($filepath, $this->data['content']);
625
                $this->builder->getLogger()->debug(sprintf('Asset "%s" saved', $filepath));
626
                if ($this->optimize) {
627
                    $this->optimize($filepath);
628
                }
629
            } catch (\Symfony\Component\Filesystem\Exception\IOException) {
630
                if (!$this->ignore_missing) {
631
                    throw new RuntimeException(sprintf('Can\'t save asset "%s".', $filepath));
632
                }
633
            }
634
        }
635
    }
636
637
    /**
638
     * Is Asset is an image in CDN.
639
     *
640
     * @return bool
641
     */
642
    public function isImageInCdn()
643
    {
644
        if ($this->data['type'] != 'image' || (bool) $this->config->get('assets.images.cdn.enabled') !== true || ($this->isSVG() && (bool) $this->config->get('assets.images.cdn.svg') !== true)) {
645
            return false;
646
        }
647
        // remote image?
648
        if ($this->data['url'] !== null && (bool) $this->config->get('assets.images.cdn.remote') !== true) {
649
            return false;
650
        }
651
652
        return true;
653
    }
654
655
    /**
656
     * Load file data.
657
     *
658
     * @throws RuntimeException
659
     */
660
    private function loadFile(string $path, bool $ignore_missing = false, ?string $remote_fallback = null, bool $force_slash = true): array
661
    {
662
        $file = [
663
            'url' => null,
664
        ];
665
666
        try {
667
            $filePath = $this->findFile($path, $remote_fallback);
668
        } catch (RuntimeException $e) {
669
            if ($ignore_missing) {
670
                $file['path'] = $path;
671
                $file['missing'] = true;
672
673
                return $file;
674
            }
675
676
            throw new RuntimeException(sprintf('Can\'t load asset file "%s" (%s).', $path, $e->getMessage()));
677
        }
678
679
        if (Util\Url::isUrl($path)) {
680
            $file['url'] = $path;
681
            $path = Util::joinPath(
682
                (string) $this->config->get('assets.target'),
683
                Util\File::getFS()->makePathRelative($filePath, $this->config->getCacheAssetsRemotePath())
684
            );
685
            // remote_fallback in assets/ ont in cache/assets/remote/
686
            if (substr(Util\File::getFS()->makePathRelative($filePath, $this->config->getCacheAssetsRemotePath()), 0, 2) == '..') {
687
                $path = Util::joinPath(
688
                    (string) $this->config->get('assets.target'),
689
                    Util\File::getFS()->makePathRelative($filePath, $this->config->getAssetsPath())
690
                );
691
            }
692
            $force_slash = true;
693
        }
694
        if ($force_slash) {
695
            $path = '/' . ltrim($path, '/');
696
        }
697
698
        list($type, $subtype) = Util\File::getMimeType($filePath);
699
        $content = Util\File::fileGetContents($filePath);
700
701
        $file['filepath'] = $filePath;
702
        $file['path'] = $path;
703
        $file['ext'] = pathinfo($path)['extension'] ?? '';
704
        $file['type'] = $type;
705
        $file['subtype'] = $subtype;
706
        $file['size'] = filesize($filePath);
707
        $file['content'] = $content;
708
        $file['missing'] = false;
709
710
        return $file;
711
    }
712
713
    /**
714
     * Try to find the file:
715
     *   1. remote (if $path is a valid URL)
716
     *   2. in static/
717
     *   3. in themes/<theme>/static/
718
     * Returns local file path or throw an exception.
719
     *
720
     * @throws RuntimeException
721
     */
722
    private function findFile(string $path, ?string $remote_fallback = null): string
723
    {
724
        // in case of remote file: save it and returns cached file path
725
        if (Util\Url::isUrl($path)) {
726
            $url = $path;
727
            $urlHost = parse_url($path, PHP_URL_HOST);
728
            $urlPath = parse_url($path, PHP_URL_PATH);
729
            $urlQuery = parse_url($path, PHP_URL_QUERY);
730
            $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
731
            // Google Fonts hack
732
            if (Util\Str::endsWith($urlPath, '/css') || Util\Str::endsWith($urlPath, '/css2')) {
733
                $extension = 'css';
734
            }
735
            $relativePath = Page::slugify(sprintf(
736
                '%s%s%s%s',
737
                $urlHost,
738
                $this->sanitize($urlPath),
739
                $urlQuery ? "-$urlQuery" : '',
740
                $urlQuery && $extension ? ".$extension" : ''
741
            ));
742
            $filePath = Util::joinFile($this->config->getCacheAssetsRemotePath(), $relativePath);
743
            // not already in cache
744
            if (!file_exists($filePath)) {
745
                try {
746
                    if (!Util\Url::isRemoteFileExists($url)) {
747
                        throw new RuntimeException(sprintf('File "%s" doesn\'t exists', $url));
748
                    }
749
                    if (false === $content = Util\File::fileGetContents($url, true)) {
750
                        throw new RuntimeException(sprintf('Can\'t get content of file "%s".', $url));
751
                    }
752
                    if (\strlen($content) <= 1) {
753
                        throw new RuntimeException(sprintf('File "%s" is empty.', $url));
754
                    }
755
                } catch (RuntimeException $e) {
756
                    // is there a fallback in assets/
757
                    if ($remote_fallback) {
758
                        $filePath = Util::joinFile($this->config->getAssetsPath(), $remote_fallback);
759
                        if (Util\File::getFS()->exists($filePath)) {
760
                            return $filePath;
761
                        }
762
                        throw new RuntimeException(sprintf('Fallback file "%s" doesn\'t exists.', $filePath));
763
                    }
764
765
                    throw new RuntimeException($e->getMessage());
766
                }
767
                if (false === $content = Util\File::fileGetContents($url, true)) {
768
                    throw new RuntimeException(sprintf('Can\'t get content of "%s"', $url));
769
                }
770
                if (\strlen($content) <= 1) {
771
                    throw new RuntimeException(sprintf('Asset at "%s" is empty', $url));
772
                }
773
                // put file in cache
774
                Util\File::getFS()->dumpFile($filePath, $content);
775
            }
776
777
            return $filePath;
778
        }
779
780
        // checks in assets/
781
        $filePath = Util::joinFile($this->config->getAssetsPath(), $path);
782
        if (Util\File::getFS()->exists($filePath)) {
783
            return $filePath;
784
        }
785
786
        // checks in each themes/<theme>/assets/
787
        foreach ($this->config->getTheme() as $theme) {
788
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
789
            if (Util\File::getFS()->exists($filePath)) {
790
                return $filePath;
791
            }
792
        }
793
794
        // checks in static/
795
        $filePath = Util::joinFile($this->config->getStaticTargetPath(), $path);
796
        if (Util\File::getFS()->exists($filePath)) {
797
            return $filePath;
798
        }
799
800
        // checks in each themes/<theme>/static/
801
        foreach ($this->config->getTheme() as $theme) {
802
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
803
            if (Util\File::getFS()->exists($filePath)) {
804
                return $filePath;
805
            }
806
        }
807
808
        throw new RuntimeException(sprintf('Can\'t find file "%s".', $path));
809
    }
810
811
    /**
812
     * Returns the width of an image/SVG.
813
     *
814
     * @throws RuntimeException
815
     */
816
    private function getWidth(): int
817
    {
818
        if ($this->data['type'] != 'image') {
819
            return 0;
820
        }
821
        if ($this->isSVG() && false !== $svg = $this->getSvgAttributes()) {
822
            return (int) $svg->width;
823
        }
824
        if (false === $size = $this->getImageSize()) {
825
            throw new RuntimeException(sprintf('Not able to get width of "%s".', $this->data['path']));
826
        }
827
828
        return $size[0];
829
    }
830
831
    /**
832
     * Returns the height of an image/SVG.
833
     *
834
     * @throws RuntimeException
835
     */
836
    private function getHeight(): int
837
    {
838
        if ($this->data['type'] != 'image') {
839
            return 0;
840
        }
841
        if ($this->isSVG() && false !== $svg = $this->getSvgAttributes()) {
842
            return (int) $svg->height;
843
        }
844
        if (false === $size = $this->getImageSize()) {
845
            throw new RuntimeException(sprintf('Not able to get height of "%s".', $this->data['path']));
846
        }
847
848
        return $size[1];
849
    }
850
851
    /**
852
     * Returns image size informations.
853
     *
854
     * @see https://www.php.net/manual/function.getimagesize.php
855
     *
856
     * @return array|false
857
     */
858
    private function getImageSize()
859
    {
860
        if (!$this->data['type'] == 'image') {
861
            return false;
862
        }
863
864
        try {
865
            if (false === $size = getimagesizefromstring($this->data['content'])) {
866
                return false;
867
            }
868
        } catch (\Exception $e) {
869
            throw new RuntimeException(sprintf('Handling asset "%s" failed: "%s"', $this->data['path_source'], $e->getMessage()));
870
        }
871
872
        return $size;
873
    }
874
875
    /**
876
     * Returns true if asset is a SVG.
877
     */
878
    private function isSVG(): bool
879
    {
880
        return \in_array($this->data['subtype'], ['image/svg', 'image/svg+xml']) || $this->data['ext'] == 'svg';
881
    }
882
883
    /**
884
     * Returns SVG attributes.
885
     *
886
     * @return \SimpleXMLElement|false
887
     */
888
    private function getSvgAttributes()
889
    {
890
        if (false === $xml = simplexml_load_string($this->data['content_source'])) {
891
            return false;
892
        }
893
894
        return $xml->attributes();
895
    }
896
897
    /**
898
     * Replaces some characters by '_'.
899
     */
900
    private function sanitize(string $string): string
901
    {
902
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
903
    }
904
905
    /**
906
     * Builds CDN image URL.
907
     */
908
    private function buildImageCdnUrl(): string
909
    {
910
        return str_replace(
911
            [
912
                '%account%',
913
                '%image_url%',
914
                '%width%',
915
                '%quality%',
916
                '%format%',
917
            ],
918
            [
919
                $this->config->get('assets.images.cdn.account'),
920
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical') ?? true]), '/'),
921
                $this->data['width'],
922
                $this->config->get('assets.images.quality') ?? 75,
923
                $this->data['ext'],
924
            ],
925
            (string) $this->config->get('assets.images.cdn.url')
926
        );
927
    }
928
}
929