Passed
Push — asset-remote ( 7df752 )
by Arnaud
04:17
created

Asset::loadFile()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 37
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
cc 5
eloc 24
c 2
b 2
f 0
nc 6
nop 4
dl 0
loc 37
rs 9.2248
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\RuntimeException;
21
use Cecil\Util;
22
use Intervention\Image\ImageManagerStatic as ImageManager;
23
use MatthiasMullie\Minify;
24
use ScssPhp\ScssPhp\Compiler;
25
use wapmorgan\Mp3Info\Mp3Info;
26
27
class Asset implements \ArrayAccess
28
{
29
    /** @var Builder */
30
    protected $builder;
31
32
    /** @var Config */
33
    protected $config;
34
35
    /** @var array */
36
    protected $data = [];
37
38
    /** @var bool */
39
    protected $fingerprinted = false;
40
41
    /** @var bool */
42
    protected $compiled = false;
43
44
    /** @var bool */
45
    protected $minified = false;
46
47
    /** @var bool */
48
    protected $optimize = false;
49
    protected $optimized = false;
50
51
    /** @var bool */
52
    protected $ignore_missing = false;
53
54
    /**
55
     * Creates an Asset from a file path or an array of files path.
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, $paths, array $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 (empty($path)) {
70
                throw new RuntimeException('The path to an asset can\'t be empty.');
71
            }
72
            if (substr($path, 0, 2) == '..') {
73
                throw new RuntimeException(\sprintf('The path to asset "%s" is wrong: it must be directly relative to "assets" or "static" directory, or a remote URL.', $path));
74
            }
75
        });
76
        $this->data = [
77
            'file'           => '',    // absolute file path
78
            'files'          => [],    // bundle: files path
79
            'filename'       => '',    // filename
80
            'path_source'    => '',    // public path to the file, before transformations
81
            'path'           => '',    // public path to the file, after transformations
82
            'missing'        => false, // if file not found, but missing ollowed 'missing' is true
83
            'ext'            => '',    // file extension
84
            'type'           => '',    // file type (e.g.: image, audio, video, etc.)
85
            'subtype'        => '',    // file media type (e.g.: image/png, audio/mp3, etc.)
86
            'size'           => 0,     // file size (in bytes)
87
            'content_source' => '',    // file content, before transformations
88
            'content'        => '',    // file content, after transformations
89
            'width'          => 0,     // width (in pixels) in case of an image
90
            'height'         => 0,     // height (in pixels) in case of an image
91
        ];
92
93
        // handles options
94
        $fingerprint = (bool) $this->config->get('assets.fingerprint.enabled');
95
        $minify = (bool) $this->config->get('assets.minify.enabled');
96
        $optimize = (bool) $this->config->get('assets.images.optimize.enabled');
97
        $filename = '';
98
        $ignore_missing = false;
99
        $remote_fallback = null;
100
        $force_slash = true;
101
        extract(is_array($options) ? $options : [], EXTR_IF_EXISTS);
102
        $this->ignore_missing = $ignore_missing;
103
104
        // fill data array with file(s) informations
105
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
106
        $cacheKey = \sprintf('%s__%s', implode('_', $paths), $this->builder->getVersion());
107
        if (!$cache->has($cacheKey)) {
108
            $pathsCount = count($paths);
109
            $file = [];
110
            for ($i = 0; $i < $pathsCount; $i++) {
111
                // loads file(s)
112
                $file[$i] = $this->loadFile($paths[$i], $ignore_missing, $remote_fallback, $force_slash);
113
                // bundle: same type/ext only
114
                if ($i > 0) {
115
                    if ($file[$i]['type'] != $file[$i - 1]['type']) {
116
                        throw new RuntimeException(\sprintf('Asset bundle type error (%s != %s).', $file[$i]['type'], $file[$i - 1]['type']));
117
                    }
118
                    if ($file[$i]['ext'] != $file[$i - 1]['ext']) {
119
                        throw new RuntimeException(\sprintf('Asset bundle extension error (%s != %s).', $file[$i]['ext'], $file[$i - 1]['ext']));
120
                    }
121
                }
122
                // missing allowed = empty path
123
                if ($file[$i]['missing']) {
124
                    $this->data['missing'] = true;
125
                    $this->data['path'] = $file[$i]['path'];
126
127
                    continue;
128
                }
129
                // set data
130
                $this->data['size'] += $file[$i]['size'];
131
                $this->data['content_source'] .= $file[$i]['content'];
132
                $this->data['content'] .= $file[$i]['content'];
133
                if ($i == 0) {
134
                    $this->data['file'] = $file[$i]['filepath'];
135
                    $this->data['filename'] = $file[$i]['path'];
136
                    $this->data['path_source'] = $file[$i]['path'];
137
                    $this->data['path'] = $file[$i]['path'];
138
                    if (!empty($filename)) { /** @phpstan-ignore-line */
139
                        $this->data['path'] = '/'.ltrim($filename, '/');
140
                    }
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
                    }
148
                }
149
                // bundle files path
150
                $this->data['files'][] = $file[$i]['filepath'];
151
            }
152
            // bundle: define path
153
            if ($pathsCount > 1 && empty($filename)) { /** @phpstan-ignore-line */
154
                switch ($this->data['ext']) {
155
                    case 'scss':
156
                    case 'css':
157
                        $this->data['path'] = '/styles.'.$file[0]['ext'];
158
                        break;
159
                    case 'js':
160
                        $this->data['path'] = '/scripts.'.$file[0]['ext'];
161
                        break;
162
                    default:
163
                        throw new RuntimeException(\sprintf('Asset bundle supports "%s" files only.', '.scss, .css and .js'));
164
                }
165
            }
166
            $cache->set($cacheKey, $this->data);
167
        }
168
        $this->data = $cache->get($cacheKey);
169
170
        // fingerprinting
171
        if ($fingerprint) {
172
            $this->fingerprint();
173
        }
174
        // compiling
175
        if ((bool) $this->config->get('assets.compile.enabled')) {
176
            $this->compile();
177
        }
178
        // minifying
179
        if ($minify) {
180
            $this->minify();
181
        }
182
        // optimizing
183
        if ($optimize) {
184
            $this->optimize = true;
185
        }
186
    }
187
188
    /**
189
     * Returns path.
190
     *
191
     * @throws RuntimeException
192
     */
193
    public function __toString(): string
194
    {
195
        try {
196
            $this->save();
197
        } catch (\Exception $e) {
198
            $this->builder->getLogger()->error($e->getMessage());
199
        }
200
201
        if ($this->builder->getConfig()->get('canonicalurl')) {
202
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
203
        }
204
205
        return $this->data['path'];
206
    }
207
208
    /**
209
     * Fingerprints a file.
210
     */
211
    public function fingerprint(): self
212
    {
213
        if ($this->fingerprinted) {
214
            return $this;
215
        }
216
217
        $fingerprint = hash('md5', $this->data['content_source']);
218
        $this->data['path'] = preg_replace(
219
            '/\.'.$this->data['ext'].'$/m',
220
            ".$fingerprint.".$this->data['ext'],
221
            $this->data['path']
222
        );
223
224
        $this->fingerprinted = true;
225
226
        return $this;
227
    }
228
229
    /**
230
     * Compiles a SCSS.
231
     *
232
     * @throws RuntimeException
233
     */
234
    public function compile(): self
235
    {
236
        if ($this->compiled) {
237
            return $this;
238
        }
239
240
        if ($this->data['ext'] != 'scss') {
241
            return $this;
242
        }
243
244
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
245
        $cacheKey = $cache->createKeyFromAsset($this, ['compiled']);
246
        if (!$cache->has($cacheKey)) {
247
            $scssPhp = new Compiler();
248
            $importDir = [];
249
            $importDir[] = Util::joinPath($this->config->getStaticPath());
250
            $importDir[] = Util::joinPath($this->config->getAssetsPath());
251
            $scssDir = $this->config->get('assets.compile.import') ?? [];
252
            $themes = $this->config->getTheme() ?? [];
253
            foreach ($scssDir as $dir) {
254
                $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir);
255
                $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir);
256
                $importDir[] = Util::joinPath(dirname($this->data['file']), $dir);
257
                foreach ($themes as $theme) {
258
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir"));
259
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir"));
260
                }
261
            }
262
            $scssPhp->setImportPaths(array_unique($importDir));
263
            // source map
264
            if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) {
265
                $importDir = [];
266
                $assetDir = (string) $this->config->get('assets.dir');
267
                $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR.$assetDir.DIRECTORY_SEPARATOR);
268
                $fileRelPath = substr($this->data['file'], $assetDirPos + 8);
269
                $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath);
270
                $importDir[] = dirname($filePath);
271
                foreach ($scssDir as $dir) {
272
                    $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir);
273
                }
274
                $scssPhp->setImportPaths(array_unique($importDir));
275
                $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE);
276
                $scssPhp->setSourceMapOptions([
277
                    'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()),
278
                    'sourceRoot'        => '/',
279
                ]);
280
            }
281
            // output style
282
            $outputStyles = ['expanded', 'compressed'];
283
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
284
            if (!in_array($outputStyle, $outputStyles)) {
285
                throw new RuntimeException(\sprintf('Scss output style "%s" doesn\'t exists.', $outputStyle));
286
            }
287
            $scssPhp->setOutputStyle($outputStyle);
288
            // variables
289
            $variables = $this->config->get('assets.compile.variables') ?? [];
290
            if (!empty($variables)) {
291
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
292
                $scssPhp->replaceVariables($variables);
293
            }
294
            // update data
295
            $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']);
296
            $this->data['ext'] = 'css';
297
            $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss();
298
            $this->compiled = true;
299
            $cache->set($cacheKey, $this->data);
300
        }
301
        $this->data = $cache->get($cacheKey);
302
303
        return $this;
304
    }
305
306
    /**
307
     * Minifying a CSS or a JS.
308
     *
309
     * @throws RuntimeException
310
     */
311
    public function minify(): self
312
    {
313
        // disable minify to preserve inline source map
314
        if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) {
315
            return $this;
316
        }
317
318
        if ($this->minified) {
319
            return $this;
320
        }
321
322
        if ($this->data['ext'] == 'scss') {
323
            $this->compile();
324
        }
325
326
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
327
            return $this;
328
        }
329
330
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
331
            $this->minified;
332
333
            return $this;
334
        }
335
336
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
337
        $cacheKey = $cache->createKeyFromAsset($this, ['minified']);
338
        if (!$cache->has($cacheKey)) {
339
            switch ($this->data['ext']) {
340
                case 'css':
341
                    $minifier = new Minify\CSS($this->data['content']);
342
                    break;
343
                case 'js':
344
                    $minifier = new Minify\JS($this->data['content']);
345
                    break;
346
                default:
347
                    throw new RuntimeException(\sprintf('Not able to minify "%s"', $this->data['path']));
348
            }
349
            $this->data['path'] = preg_replace(
350
                '/\.'.$this->data['ext'].'$/m',
351
                '.min.'.$this->data['ext'],
352
                $this->data['path']
353
            );
354
            $this->data['content'] = $minifier->minify();
355
            $this->minified = true;
356
            $cache->set($cacheKey, $this->data);
357
        }
358
        $this->data = $cache->get($cacheKey);
359
360
        return $this;
361
    }
362
363
    /**
364
     * Optimizing an image.
365
     */
366
    public function optimize(string $filepath): self
367
    {
368
        if ($this->data['type'] != 'image') {
369
            return $this;
370
        }
371
372
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
373
        $tags = ['optimized'];
374
        if ($this->data['width']) {
375
            array_unshift($tags, "{$this->data['width']}x");
376
        }
377
        $cacheKey = $cache->createKeyFromAsset($this, $tags);
378
        if (!$cache->has($cacheKey)) {
379
            $message = $this->data['path'];
380
            $sizeBefore = filesize($filepath);
381
            Optimizer::create($this->config->get('assets.images.quality') ?? 75)->optimize($filepath);
382
            $sizeAfter = filesize($filepath);
383
            if ($sizeAfter < $sizeBefore) {
384
                $message = \sprintf(
385
                    '%s (%s Ko -> %s Ko)',
386
                    $message,
387
                    ceil($sizeBefore / 1000),
388
                    ceil($sizeAfter / 1000)
389
                );
390
            }
391
            $this->data['content'] = Util\File::fileGetContents($filepath);
392
            $cache->set($cacheKey, $this->data);
393
            $this->builder->getLogger()->debug(\sprintf('Asset "%s" optimized', $message));
394
        }
395
        $this->data = $cache->get($cacheKey);
396
        $this->optimized = true;
397
398
        return $this;
399
    }
400
401
    /**
402
     * Resizes an image with a new $width.
403
     *
404
     * @throws RuntimeException
405
     */
406
    public function resize(int $width): self
407
    {
408
        if ($this->data['missing']) {
409
            throw new RuntimeException(\sprintf('Not able to resize "%s": file not found', $this->data['path']));
410
        }
411
        if ($this->data['type'] != 'image') {
412
            throw new RuntimeException(\sprintf('Not able to resize "%s": not an image', $this->data['path']));
413
        }
414
        if ($width >= $this->getWidth()) {
415
            return $this;
416
        }
417
418
        $assetResized = clone $this;
419
        $assetResized->data['width'] = $width;
420
421
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
422
        $cacheKey = $cache->createKeyFromAsset($assetResized, ["{$width}x"]);
423
        if (!$cache->has($cacheKey)) {
424
            if ($assetResized->data['type'] !== 'image') {
425
                throw new RuntimeException(\sprintf('Not able to resize "%s"', $assetResized->data['path']));
426
            }
427
            if (!extension_loaded('gd')) {
428
                throw new RuntimeException('GD extension is required to use images resize.');
429
            }
430
431
            try {
432
                $img = ImageManager::make($assetResized->data['content_source']);
433
                $img->resize($width, null, function (\Intervention\Image\Constraint $constraint) {
434
                    $constraint->aspectRatio();
435
                    $constraint->upsize();
436
                });
437
            } catch (\Exception $e) {
438
                throw new RuntimeException(\sprintf('Not able to resize image "%s": %s', $assetResized->data['path'], $e->getMessage()));
439
            }
440
            $assetResized->data['path'] = '/'.Util::joinPath(
441
                (string) $this->config->get('assets.target'),
442
                (string) $this->config->get('assets.images.resize.dir'),
443
                (string) $width,
444
                $assetResized->data['path']
445
            );
446
447
            try {
448
                $assetResized->data['content'] = (string) $img->encode($assetResized->data['ext'], $this->config->get('assets.images.quality'));
449
                $assetResized->data['height'] = $assetResized->getHeight();
450
            } catch (\Exception $e) {
451
                throw new RuntimeException(\sprintf('Not able to encode image "%s": %s', $assetResized->data['path'], $e->getMessage()));
452
            }
453
454
            $cache->set($cacheKey, $assetResized->data);
455
        }
456
        $assetResized->data = $cache->get($cacheKey);
457
458
        return $assetResized;
459
    }
460
461
    /**
462
     * Returns the data URL of an image.
463
     *
464
     * @throws RuntimeException
465
     */
466
    public function dataurl(): string
467
    {
468
        if ($this->data['type'] !== 'image') {
469
            throw new RuntimeException(\sprintf('Can\'t get data URL of "%s"', $this->data['path']));
470
        }
471
472
        return (string) ImageManager::make($this->data['content'])->encode('data-url', $this->config->get('assets.images.quality'));
473
    }
474
475
    /**
476
     * Implements \ArrayAccess.
477
     */
478
    #[\ReturnTypeWillChange]
479
    public function offsetSet($offset, $value): void
480
    {
481
        if (!is_null($offset)) {
482
            $this->data[$offset] = $value;
483
        }
484
    }
485
486
    /**
487
     * Implements \ArrayAccess.
488
     */
489
    #[\ReturnTypeWillChange]
490
    public function offsetExists($offset): bool
491
    {
492
        return isset($this->data[$offset]);
493
    }
494
495
    /**
496
     * Implements \ArrayAccess.
497
     */
498
    #[\ReturnTypeWillChange]
499
    public function offsetUnset($offset): void
500
    {
501
        unset($this->data[$offset]);
502
    }
503
504
    /**
505
     * Implements \ArrayAccess.
506
     */
507
    #[\ReturnTypeWillChange]
508
    public function offsetGet($offset)
509
    {
510
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
511
    }
512
513
    /**
514
     * Hashing content of an asset with the specified algo, sha384 by default.
515
     * Used for SRI (Subresource Integrity).
516
     *
517
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
518
     */
519
    public function getIntegrity(string $algo = 'sha384'): string
520
    {
521
        return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
522
    }
523
524
    /**
525
     * Returns the width of an image/SVG.
526
     *
527
     * @throws RuntimeException
528
     */
529
    public function getWidth(): int
530
    {
531
        if ($this->data['type'] != 'image') {
532
            return 0;
533
        }
534
        if ($this->isSVG() && false !== $svg = $this->getSvgAttributes()) {
535
            return (int) $svg->width;
536
        }
537
        if (false === $size = $this->getImageSize()) {
538
            throw new RuntimeException(\sprintf('Not able to get width of "%s"', $this->data['path']));
539
        }
540
541
        return $size[0];
542
    }
543
544
    /**
545
     * Returns the height of an image/SVG.
546
     *
547
     * @throws RuntimeException
548
     */
549
    public function getHeight(): int
550
    {
551
        if ($this->data['type'] != 'image') {
552
            return 0;
553
        }
554
        if ($this->isSVG() && false !== $svg = $this->getSvgAttributes()) {
555
            return (int) $svg->height;
556
        }
557
        if (false === $size = $this->getImageSize()) {
558
            throw new RuntimeException(\sprintf('Not able to get height of "%s"', $this->data['path']));
559
        }
560
561
        return $size[1];
562
    }
563
564
    /**
565
     * Returns MP3 file infos.
566
     *
567
     * @see https://github.com/wapmorgan/Mp3Info
568
     */
569
    public function getAudio(): Mp3Info
570
    {
571
        if ($this->data['type'] !== 'audio') {
572
            throw new RuntimeException(\sprintf('Not able to get audio infos of "%s"', $this->data['path']));
573
        }
574
575
        return new Mp3Info($this->data['file']);
576
    }
577
578
    /**
579
     * Saves file.
580
     * Note: a file from `static/` with the same name will NOT be overridden.
581
     *
582
     * @throws RuntimeException
583
     */
584
    public function save(): void
585
    {
586
        $filepath = Util::joinFile($this->config->getOutputPath(), $this->data['path']);
587
        if (!$this->builder->getBuildOptions()['dry-run'] && !Util\File::getFS()->exists($filepath)) {
588
            try {
589
                Util\File::getFS()->dumpFile($filepath, $this->data['content']);
590
                $this->builder->getLogger()->debug(\sprintf('Asset "%s" saved', $this->data['path']));
591
                if ($this->optimize) {
592
                    $this->optimize($filepath);
593
                }
594
            } catch (\Symfony\Component\Filesystem\Exception\IOException $e) {
595
                if (!$this->ignore_missing) {
596
                    throw new RuntimeException(\sprintf('Can\'t save asset "%s"', $filepath));
597
                }
598
            }
599
        }
600
    }
601
602
    /**
603
     * Load file data.
604
     *
605
     * @throws RuntimeException
606
     */
607
    private function loadFile(string $path, bool $ignore_missing = false, ?string $remote_fallback = null, bool $force_slash = true): array
608
    {
609
        $file = [];
610
611
        if (false === $filePath = $this->findFile($path, $remote_fallback)) {
612
            if ($ignore_missing) {
613
                $file['path'] = $path;
614
                $file['missing'] = true;
615
616
                return $file;
617
            }
618
619
            throw new RuntimeException(\sprintf('Asset file "%s" doesn\'t exist', $path));
620
        }
621
622
        if (Util\Url::isUrl($path)) {
623
            $path = Util\File::getFS()->makePathRelative($filePath, $this->config->getCacheAssetsRemotePath());
624
            $path = Util::joinPath((string) $this->config->get('assets.target'), $path);
625
            $force_slash = true;
626
        }
627
        if ($force_slash) {
628
            $path = '/'.ltrim($path, '/');
629
        }
630
631
        list($type, $subtype) = Util\File::getMimeType($filePath);
632
        $content = Util\File::fileGetContents($filePath);
633
634
        $file['filepath'] = $filePath;
635
        $file['path'] = $path;
636
        $file['ext'] = pathinfo($path)['extension'] ?? '';
637
        $file['type'] = $type;
638
        $file['subtype'] = $subtype;
639
        $file['size'] = filesize($filePath);
640
        $file['content'] = $content;
641
        $file['missing'] = false;
642
643
        return $file;
644
    }
645
646
    /**
647
     * Try to find the file:
648
     *   1. remote (if $path is a valid URL)
649
     *   2. in static/
650
     *   3. in themes/<theme>/static/
651
     * Returns local file path or false if file don't exists.
652
     *
653
     * @throws RuntimeException
654
     *
655
     * @return string|false
656
     */
657
    private function findFile(string $path, ?string $remote_fallback = null)
658
    {
659
        // in case of remote file: save it and returns cached file path
660
        if (Util\Url::isUrl($path)) {
661
            $url = $path;
662
            $urlHost = parse_url($path, PHP_URL_HOST);
663
            $urlPath = parse_url($path, PHP_URL_PATH);
664
            $urlQuery = parse_url($path, PHP_URL_QUERY);
665
            $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
666
            $relativePath = Page::slugify(\sprintf(
667
                '%s%s-%s%s',
668
                $urlHost,
669
                $this->sanitize($urlPath),
670
                $urlQuery ? "-$urlQuery" : '',
671
                $urlQuery && $extension ? ".$extension" : ''
672
            ));
673
            $filePath = Util::joinFile($this->config->getCacheAssetsRemotePath(), $relativePath);
674
            if (!file_exists($filePath)) {
675
                if (!Util\Url::isRemoteFileExists($url)) {
676
                    // is there a fallback in assets/
677
                    if ($remote_fallback) {
678
                        $filePath = Util::joinFile($this->config->getAssetsPath(), $remote_fallback);
679
                        if (Util\File::getFS()->exists($filePath)) {
680
                            return $filePath;
681
                        }
682
                    }
683
684
                    return false;
685
                }
686
                if (false === $content = Util\File::fileGetContents($url, true)) {
687
                    return false;
688
                }
689
                if (strlen($content) <= 1) {
690
                    throw new RuntimeException(\sprintf('Asset at "%s" is empty', $url));
691
                }
692
                Util\File::getFS()->dumpFile($filePath, $content);
693
            }
694
695
            return $filePath;
696
        }
697
698
        // checks in assets/
699
        $filePath = Util::joinFile($this->config->getAssetsPath(), $path);
700
        if (Util\File::getFS()->exists($filePath)) {
701
            return $filePath;
702
        }
703
704
        // checks in each themes/<theme>/assets/
705
        foreach ($this->config->getTheme() as $theme) {
706
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
707
            if (Util\File::getFS()->exists($filePath)) {
708
                return $filePath;
709
            }
710
        }
711
712
        // checks in static/
713
        $filePath = Util::joinFile($this->config->getStaticTargetPath(), $path);
714
        if (Util\File::getFS()->exists($filePath)) {
715
            return $filePath;
716
        }
717
718
        // checks in each themes/<theme>/static/
719
        foreach ($this->config->getTheme() as $theme) {
720
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
721
            if (Util\File::getFS()->exists($filePath)) {
722
                return $filePath;
723
            }
724
        }
725
726
        return false;
727
    }
728
729
    /**
730
     * Returns image size informations.
731
     *
732
     * @see https://www.php.net/manual/function.getimagesize.php
733
     *
734
     * @return array|false
735
     */
736
    private function getImageSize()
737
    {
738
        if (!$this->data['type'] == 'image') {
739
            return false;
740
        }
741
742
        try {
743
            if (false === $size = getimagesizefromstring($this->data['content'])) {
744
                return false;
745
            }
746
        } catch (\Exception $e) {
747
            throw new RuntimeException(\sprintf('Handling asset "%s" failed: "%s"', $this->data['path_source'], $e->getMessage()));
748
        }
749
750
        return $size;
751
    }
752
753
    /**
754
     * Returns true if asset is a SVG.
755
     */
756
    private function isSVG(): bool
757
    {
758
        return in_array($this->data['subtype'], ['image/svg', 'image/svg+xml']) || $this->data['ext'] == 'svg';
759
    }
760
761
    /**
762
     * Returns SVG attributes.
763
     *
764
     * @return \SimpleXMLElement|false
765
     */
766
    private function getSvgAttributes()
767
    {
768
        if (false === $xml = simplexml_load_string($this->data['content_source'])) {
769
            return false;
770
        }
771
772
        return $xml->attributes();
773
    }
774
775
    /**
776
     * Replaces some characters by '_'.
777
     */
778
    private function sanitize(string $string): string
779
    {
780
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
781
    }
782
}
783