Passed
Push — analysis-Znp5Gg ( 8e87eb )
by Arnaud
04:53 queued 10s
created

Asset::getRemoteFileContent()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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