• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Cecilapp / Cecil / 14532758805

18 Apr 2025 09:06AM UTC coverage: 83.633%. First build
14532758805

Pull #2148

github

web-flow
Merge 004f11f49 into bc7c717e4
Pull Request #2148: refactor: configuration and cache

315 of 376 new or added lines in 26 files covered. (83.78%)

3025 of 3617 relevant lines covered (83.63%)

0.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

82.25
/src/Assets/Asset.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <arnaud@ligny.fr>
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
     *     '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;
1✔
71
        $this->config = $builder->getConfig();
1✔
72
        $paths = \is_array($paths) ? $paths : [$paths];
1✔
73
        // checks path(s)
74
        array_walk($paths, function ($path) {
1✔
75
            // must be a string
76
            if (!\is_string($path)) {
1✔
77
                throw new RuntimeException(\sprintf('The path of an asset must be a string ("%s" given).', \gettype($path)));
×
78
            }
79
            // can't be empty
80
            if (empty($path)) {
1✔
81
                throw new RuntimeException('The path of an asset can\'t be empty.');
×
82
            }
83
            // can't be relative
84
            if (substr($path, 0, 2) == '..') {
1✔
NEW
85
                throw new RuntimeException(\sprintf('The path of asset "%s" is wrong: it must be directly relative to `assets` or `static` directory, or a remote URL.', $path));
×
86
            }
87
        });
1✔
88
        $this->data = [
1✔
89
            'file'     => '',    // absolute file path
1✔
90
            'files'    => [],    // array of absolute files path
1✔
91
            'path'     => '',    // public path
1✔
92
            '_path'    => '',    // public path before any modification
1✔
93
            'url'      => null,  // URL if it's a remote file
1✔
94
            'missing'  => false, // if file not found but missing allowed: 'missing' is true
1✔
95
            'ext'      => '',    // file extension
1✔
96
            'type'     => '',    // file type (e.g.: image, audio, video, etc.)
1✔
97
            'subtype'  => '',    // file media type (e.g.: image/png, audio/mp3, etc.)
1✔
98
            'size'     => 0,     // file size (in bytes)
1✔
99
            'width'    => 0,     // image width (in pixels)
1✔
100
            'height'   => 0,     // image height (in pixels)
1✔
101
            'exif'     => [],    // image exif data
1✔
102
            'content'  => '',    // file content
1✔
103
        ];
1✔
104

105
        // handles options
106
        $fingerprint = $this->config->isEnabled('assets.fingerprint');
1✔
107
        $minify = $this->config->isEnabled('assets.minify');
1✔
108
        $optimize = $this->config->isEnabled('assets.images.optimize');
1✔
109
        $filename = '';
1✔
110
        $ignore_missing = false;
1✔
111
        $fallback = null;
1✔
112
        $force_slash = true;
1✔
113
        extract(\is_array($options) ? $options : [], EXTR_IF_EXISTS);
1✔
114

115
        /*
116
        $options = array_merge(
117
            [
118
                'fingerprint'    => $this->config->isEnabled('assets.fingerprint'),
119
                'minify'         => $this->config->isEnabled('assets.minify'),
120
                'optimize'       => $this->config->isEnabled('assets.images.optimize'),
121
                'filename'       => '',
122
                'ignore_missing' => false,
123
                'fallback'       => null,
124
                'force_slash'    => true,
125
            ],
126
            \is_array($options) ? $options : []
127
        );
128
        $tags = [];
129
        foreach ($options as $key => $value) {
130
            if (\is_bool($value) && $value === true) {
131
                $tags[] = $key;
132
            }
133
            if (\is_string($value) && !empty($value)) {
134
                $tags[] = $value;
135
            }
136
        }
137
        // DEBUG
138
        echo implode('_', $tags) . "\n";
139
        echo hash('crc32', implode('_', $tags)) . "\n";
140
        die('debug');
141
        */
142

143
        // cache
144
        //$cache = new Cache($this->builder, 'assets');
145
        //$cacheKey = $cache->createKeyFromAsset($this, $fingerprint ? ['fingerprinted'] : []);
146

147
        //$cacheKey = \sprintf('%s__%s', $filename ?: implode('_', $paths), $this->builder->getVersion());
148

149
        // locate file(s) and get content
150
        $pathsCount = \count($paths);
1✔
151
        for ($i = 0; $i < $pathsCount; $i++) {
1✔
152
            try {
153
                $this->data['missing'] = false;
1✔
154
                $locate = $this->locateFile($paths[$i], $fallback);
1✔
155
                $file = $locate['file'];
1✔
156
                $path = $locate['path'];
1✔
157
                $type = Util\File::getMediaType($file)[0];
1✔
158
                if ($i > 0) { // bundle
1✔
159
                    if ($type != $this->data['type']) {
1✔
NEW
160
                        throw new RuntimeException(\sprintf('Asset bundle type error (%s != %s).', $type, $this->data['type']));
×
161
                    }
162
                }
163
                $this->data['file'] = $file;
1✔
164
                $this->data['files'][] = $file;
1✔
165
                $this->data['path'] = $path;
1✔
166
                $this->data['url'] = Util\File::isRemote($paths[$i]) ? $paths[$i] : null;
1✔
167
                $this->data['ext'] = Util\File::getExtension($file);
1✔
168
                $this->data['type'] = $type;
1✔
169
                $this->data['subtype'] = Util\File::getMediaType($file)[1];
1✔
170
                $this->data['size'] += filesize($file);
1✔
171
                $this->data['content'] .= Util\File::fileGetContents($file);
1✔
172
                // bundle default filename
173
                if ($pathsCount > 1 && empty($filename)) {
1✔
174
                    switch ($this->data['ext']) {
1✔
175
                        case 'scss':
1✔
176
                        case 'css':
1✔
177
                            $filename = 'styles.css';
1✔
178
                            break;
1✔
179
                        case 'js':
1✔
180
                            $filename = 'scripts.js';
1✔
181
                            break;
1✔
182
                        default:
NEW
183
                            throw new RuntimeException(\sprintf('Asset bundle supports %s files only.', '.scss, .css and .js'));
×
184
                    }
185
                }
186
                // apply bundle filename to path
187
                if (!empty($filename)) {
1✔
188
                    $this->data['path'] = '/' . ltrim($filename, '/');
1✔
189
                }
190
                // force root slash
191
                if ($force_slash) {
1✔
192
                    $this->data['path'] = '/' . ltrim($this->data['path'], '/');
1✔
193
                }
194
                $this->data['_path'] = $this->data['path'];
1✔
195
            } catch (RuntimeException $e) {
1✔
196
                if ($ignore_missing) {
1✔
197
                    $this->data['missing'] = true;
1✔
198
                    continue;
1✔
199
                }
NEW
200
                throw new RuntimeException(\sprintf('Can\'t handle asset "%s" (%s).', $paths[$i], $e->getMessage()));
×
201
            }
202
        }
203

204
        // missing
205
        if ($this->data['missing']) {
1✔
206
            return;
1✔
207
        }
208

209
        // cache
210
        $cache = new Cache($this->builder, 'assets');
1✔
211
        $cacheKey = $cache->createKeyFromAsset($this, $fingerprint ? ['fingerprinted'] : []);
1✔
212
        if (!$cache->has($cacheKey)) {
1✔
213
            // image: width, height and exif
214
            if ($this->data['type'] == 'image') {
1✔
215
                $this->data['width'] = $this->getWidth();
1✔
216
                $this->data['height'] = $this->getHeight();
1✔
217
                if ($this->data['subtype'] == 'image/jpeg') {
1✔
218
                    $this->data['exif'] = Util\File::readExif($this->data['file']);
1✔
219
                }
220
            }
221
            // fingerprinting
222
            if ($fingerprint) {
1✔
NEW
223
                $this->fingerprint();
×
224
            }
225
            $cache->set($cacheKey, $this->data);
1✔
226
            $this->builder->getLogger()->debug(\sprintf('Asset created: "%s"', $this->data['path']));
1✔
227
            // optimizing images files (in cache)
228
            if ($optimize && $this->data['type'] == 'image' && !$this->isImageInCdn()) {
1✔
229
                $this->optimize($cache->getContentFilePathname($this->data['path']), $this->data['path']);
1✔
230
            }
231
        }
232
        $this->data = $cache->get($cacheKey);
1✔
233

234
        // compiling Sass files
235
        $this->compile();
1✔
236
        // minifying (CSS and JavScript files)
237
        if ($minify) {
1✔
238
            $this->minify();
1✔
239
        }
240
    }
241

242
    /**
243
     * Returns path.
244
     */
245
    public function __toString(): string
246
    {
247
        $this->save();
1✔
248

249
        if ($this->isImageInCdn()) {
1✔
250
            return $this->buildImageCdnUrl();
×
251
        }
252

253
        if ($this->builder->getConfig()->isEnabled('canonicalurl')) {
1✔
254
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
×
255
        }
256

257
        return $this->data['path'];
1✔
258
    }
259

260
    /**
261
     * Compiles a SCSS.
262
     *
263
     * @throws RuntimeException
264
     */
265
    public function compile(): self
266
    {
267
        if ($this->compiled) {
1✔
268
            return $this;
1✔
269
        }
270

271
        if ($this->data['ext'] != 'scss') {
1✔
272
            return $this;
1✔
273
        }
274

275
        $cache = new Cache($this->builder, 'assets');
1✔
276
        $cacheKey = $cache->createKeyFromAsset($this, ['compiled']);
1✔
277
        if (!$cache->has($cacheKey)) {
1✔
278
            $scssPhp = new Compiler();
1✔
279
            // import paths
280
            $importDir = [];
1✔
281
            $importDir[] = Util::joinPath($this->config->getStaticPath());
1✔
282
            $importDir[] = Util::joinPath($this->config->getAssetsPath());
1✔
283
            $scssDir = (array) $this->config->get('assets.compile.import');
1✔
284
            $themes = $this->config->getTheme() ?? [];
1✔
285
            foreach ($scssDir as $dir) {
1✔
286
                $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir);
1✔
287
                $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir);
1✔
288
                $importDir[] = Util::joinPath(\dirname($this->data['file']), $dir);
1✔
289
                foreach ($themes as $theme) {
1✔
290
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir"));
1✔
291
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir"));
1✔
292
                }
293
            }
294
            $scssPhp->setQuietDeps(true);
1✔
295
            $scssPhp->setImportPaths(array_unique($importDir));
1✔
296
            // source map
297
            if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
1✔
298
                $importDir = [];
×
299
                $assetDir = (string) $this->config->get('assets.dir');
×
300
                $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR . $assetDir . DIRECTORY_SEPARATOR);
×
301
                $fileRelPath = substr($this->data['file'], $assetDirPos + 8);
×
302
                $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath);
×
303
                $importDir[] = \dirname($filePath);
×
304
                foreach ($scssDir as $dir) {
×
305
                    $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir);
×
306
                }
307
                $scssPhp->setImportPaths(array_unique($importDir));
×
308
                $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE);
×
309
                $scssPhp->setSourceMapOptions([
×
310
                    'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()),
×
311
                    'sourceRoot'        => '/',
×
312
                ]);
×
313
            }
314
            // output style
315
            $outputStyles = ['expanded', 'compressed'];
1✔
316
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
1✔
317
            if (!\in_array($outputStyle, $outputStyles)) {
1✔
318
                throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
×
319
            }
320
            $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
1✔
321
            // variables
322
            $variables = $this->config->get('assets.compile.variables');
1✔
323
            if (!empty($variables)) {
1✔
324
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
1✔
325
                $scssPhp->replaceVariables($variables);
1✔
326
            }
327
            // debug
328
            if ($this->builder->isDebug()) {
1✔
329
                $scssPhp->setQuietDeps(false);
1✔
330
                $this->builder->getLogger()->debug(\sprintf("SCSS compiler imported paths:\n%s", Util\Str::arrayToList(array_unique($importDir))));
1✔
331
            }
332
            // update data
333
            $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']);
1✔
334
            $this->data['ext'] = 'css';
1✔
335
            $this->data['type'] = 'text';
1✔
336
            $this->data['subtype'] = 'text/css';
1✔
337
            $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss();
1✔
338
            $this->data['size'] = \strlen($this->data['content']);
1✔
339
            $cache->set($cacheKey, $this->data);
1✔
340
            $this->compiled = true;
1✔
341
            $this->builder->getLogger()->debug(\sprintf('Asset compiled: "%s"', $this->data['path']));
1✔
342
        }
343
        $this->data = $cache->get($cacheKey);
1✔
344

345
        return $this;
1✔
346
    }
347

348
    /**
349
     * Minifying a CSS or a JS.
350
     *
351
     * @throws RuntimeException
352
     */
353
    public function minify(): self
354
    {
355
        // in debug mode, disable minify to preserve inline source map
356
        if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
1✔
357
            return $this;
×
358
        }
359

360
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
1✔
361
            return $this;
×
362
        }
363

364
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
1✔
365
            $this->minified = true;
×
366
        }
367

368
        if ($this->minified) {
1✔
369
            return $this;
×
370
        }
371

372
        if ($this->data['ext'] == 'scss') {
1✔
NEW
373
            $this->compile();
×
374
        }
375

376
        $cache = new Cache($this->builder, 'assets');
1✔
377
        $cacheKey = $cache->createKeyFromAsset($this, ['minified']);
1✔
378
        if (!$cache->has($cacheKey)) {
1✔
379
            switch ($this->data['ext']) {
1✔
380
                case 'css':
1✔
381
                    $minifier = new Minify\CSS($this->data['content']);
1✔
382
                    break;
1✔
383
                case 'js':
1✔
384
                    $minifier = new Minify\JS($this->data['content']);
1✔
385
                    break;
1✔
386
                default:
387
                    throw new RuntimeException(\sprintf('Not able to minify "%s".', $this->data['path']));
×
388
            }
389
            $this->data['content'] = $minifier->minify();
1✔
390
            $this->data['size'] = \strlen($this->data['content']);
1✔
391
            $cache->set($cacheKey, $this->data);
1✔
392
            $this->minified = true;
1✔
393
            $this->builder->getLogger()->debug(\sprintf('Asset minified: "%s"', $this->data['path']));
1✔
394
        }
395
        $this->data = $cache->get($cacheKey);
1✔
396

397
        return $this;
1✔
398
    }
399

400
    /**
401
     * Add hash to the file name.
402
     */
403
    public function fingerprint(): self
404
    {
405
        if ($this->fingerprinted) {
1✔
NEW
406
            return $this;
×
407
        }
408

409
        $cache = new Cache($this->builder, 'assets');
1✔
410
        $cacheKey = $cache->createKeyFromAsset($this, ['fingerprinted']);
1✔
411
        if (!$cache->has($cacheKey)) {
1✔
412
            $hash = hash('md5', $this->data['content']);
1✔
413
            $this->data['path'] = preg_replace(
1✔
414
                '/\.' . $this->data['ext'] . '$/m',
1✔
415
                ".$hash." . $this->data['ext'],
1✔
416
                $this->data['path']
1✔
417
            );
1✔
418
            $cache->set($cacheKey, $this->data);
1✔
419
            $this->fingerprinted = true;
1✔
420
            $this->builder->getLogger()->debug(\sprintf('Asset fingerprinted: "%s"', $this->data['path']));
1✔
421
        }
422
        $this->data = $cache->get($cacheKey);
1✔
423

424
        return $this;
1✔
425
    }
426

427
    /**
428
     * Optimizing $filepath image.
429
     * Returns the new file size.
430
     */
431
    public function optimize(string $filepath, string $path): int
432
    {
433
        $quality = (int) $this->config->get('assets.images.quality');
1✔
434
        $message = \sprintf('Asset processed: "%s"', $path);
1✔
435
        $sizeBefore = filesize($filepath);
1✔
436
        Optimizer::create($quality)->optimize($filepath);
1✔
437
        $sizeAfter = filesize($filepath);
1✔
438
        if ($sizeAfter < $sizeBefore) {
1✔
439
            $message = \sprintf(
1✔
440
                'Asset optimized: "%s" (%s Ko -> %s Ko)',
1✔
441
                $path,
1✔
442
                ceil($sizeBefore / 1000),
1✔
443
                ceil($sizeAfter / 1000)
1✔
444
            );
1✔
445
        }
446
        $this->builder->getLogger()->debug($message);
1✔
447

448
        return $sizeAfter;
1✔
449
    }
450

451
    /**
452
     * Resizes an image with a new $width.
453
     *
454
     * @throws RuntimeException
455
     */
456
    public function resize(int $width): self
457
    {
458
        if ($this->data['missing']) {
1✔
459
            throw new RuntimeException(\sprintf('Not able to resize "%s": file not found.', $this->data['path']));
×
460
        }
461
        if ($this->data['type'] != 'image') {
1✔
462
            throw new RuntimeException(\sprintf('Not able to resize "%s": not an image.', $this->data['path']));
×
463
        }
464
        if ($width >= $this->data['width']) {
1✔
465
            return $this;
1✔
466
        }
467

468
        $assetResized = clone $this;
1✔
469
        $assetResized->data['width'] = $width;
1✔
470

471
        if ($this->isImageInCdn()) {
1✔
472
            $assetResized->data['height'] = round($this->data['height'] / ($this->data['width'] / $width));
×
473

474
            return $assetResized; // returns asset with the new dimensions only: CDN do the rest of the job
×
475
        }
476

477
        $quality = (int) $this->config->get('assets.images.quality');
1✔
478
        $cache = new Cache($this->builder, 'assets');
1✔
479
        $cacheKey = $cache->createKeyFromAsset($assetResized, ["{$width}x", "q$quality"]);
1✔
480
        if (!$cache->has($cacheKey)) {
1✔
481
            $assetResized->data['content'] = Image::resize($assetResized, $width, $quality);
1✔
482
            $assetResized->data['path'] = '/' . Util::joinPath(
1✔
483
                (string) $this->config->get('assets.target'),
1✔
484
                'thumbnails',
1✔
485
                (string) $width,
1✔
486
                $assetResized->data['path']
1✔
487
            );
1✔
488
            $assetResized->data['height'] = $assetResized->getHeight();
1✔
489
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
1✔
490

491
            $cache->set($cacheKey, $assetResized->data);
1✔
492
            $this->builder->getLogger()->debug(\sprintf('Asset resized: "%s" (%sx)', $assetResized->data['path'], $width));
1✔
493
        }
494
        $assetResized->data = $cache->get($cacheKey);
1✔
495

496
        return $assetResized;
1✔
497
    }
498

499
    /**
500
     * Converts an image asset to $format format.
501
     *
502
     * @throws RuntimeException
503
     */
504
    public function convert(string $format, ?int $quality = null): self
505
    {
506
        if ($this->data['type'] != 'image') {
1✔
507
            throw new RuntimeException(\sprintf('Not able to convert "%s" (%s) to %s: not an image.', $this->data['path'], $this->data['type'], $format));
×
508
        }
509

510
        if ($quality === null) {
1✔
511
            $quality = (int) $this->config->get('assets.images.quality');
1✔
512
        }
513

514
        $asset = clone $this;
1✔
515
        $asset['ext'] = $format;
1✔
516
        $asset->data['subtype'] = "image/$format";
1✔
517

518
        if ($this->isImageInCdn()) {
1✔
519
            return $asset; // returns the asset with the new extension only: CDN do the rest of the job
×
520
        }
521

522
        $cache = new Cache($this->builder, 'assets');
1✔
523
        $tags = ["q$quality"];
1✔
524
        if ($this->data['width']) {
1✔
525
            array_unshift($tags, "{$this->data['width']}x");
1✔
526
        }
527
        $cacheKey = $cache->createKeyFromAsset($asset, $tags);
1✔
528
        if (!$cache->has($cacheKey)) {
1✔
529
            $asset->data['content'] = Image::convert($asset, $format, $quality);
1✔
530
            $asset->data['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']);
1✔
531
            $asset->data['size'] = \strlen($asset->data['content']);
1✔
532
            $cache->set($cacheKey, $asset->data);
1✔
533
            $this->builder->getLogger()->debug(\sprintf('Asset converted: "%s" (%s -> %s)', $asset->data['path'], $this->data['ext'], $format));
1✔
534
        }
535
        $asset->data = $cache->get($cacheKey);
1✔
536

537
        return $asset;
1✔
538
    }
539

540
    /**
541
     * Converts an image asset to WebP format.
542
     *
543
     * @throws RuntimeException
544
     */
545
    public function webp(?int $quality = null): self
546
    {
547
        return $this->convert('webp', $quality);
1✔
548
    }
549

550
    /**
551
     * Converts an image asset to AVIF format.
552
     *
553
     * @throws RuntimeException
554
     */
555
    public function avif(?int $quality = null): self
556
    {
557
        return $this->convert('avif', $quality);
1✔
558
    }
559

560
    /**
561
     * Implements \ArrayAccess.
562
     */
563
    #[\ReturnTypeWillChange]
564
    public function offsetSet($offset, $value): void
565
    {
566
        if (!\is_null($offset)) {
1✔
567
            $this->data[$offset] = $value;
1✔
568
        }
569
    }
570

571
    /**
572
     * Implements \ArrayAccess.
573
     */
574
    #[\ReturnTypeWillChange]
575
    public function offsetExists($offset): bool
576
    {
577
        return isset($this->data[$offset]);
1✔
578
    }
579

580
    /**
581
     * Implements \ArrayAccess.
582
     */
583
    #[\ReturnTypeWillChange]
584
    public function offsetUnset($offset): void
585
    {
586
        unset($this->data[$offset]);
×
587
    }
588

589
    /**
590
     * Implements \ArrayAccess.
591
     */
592
    #[\ReturnTypeWillChange]
593
    public function offsetGet($offset)
594
    {
595
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
1✔
596
    }
597

598
    /**
599
     * Hashing content of an asset with the specified algo, sha384 by default.
600
     * Used for SRI (Subresource Integrity).
601
     *
602
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
603
     */
604
    public function getIntegrity(string $algo = 'sha384'): string
605
    {
606
        return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
1✔
607
    }
608

609
    /**
610
     * Returns MP3 file infos.
611
     *
612
     * @see https://github.com/wapmorgan/Mp3Info
613
     */
614
    public function getAudio(): Mp3Info
615
    {
616
        if ($this->data['type'] !== 'audio') {
1✔
617
            throw new RuntimeException(\sprintf('Not able to get audio infos of "%s".', $this->data['path']));
×
618
        }
619

620
        return new Mp3Info($this->data['file']);
1✔
621
    }
622

623
    /**
624
     * Returns MP4 file infos.
625
     *
626
     * @see https://github.com/clwu88/php-read-mp4info
627
     */
628
    public function getVideo(): array
629
    {
630
        if ($this->data['type'] !== 'video') {
1✔
631
            throw new RuntimeException(\sprintf('Not able to get video infos of "%s".', $this->data['path']));
×
632
        }
633

634
        return (array) \Clwu\Mp4::getInfo($this->data['file']);
1✔
635
    }
636

637
    /**
638
     * Returns the Data URL (encoded in Base64).
639
     *
640
     * @throws RuntimeException
641
     */
642
    public function dataurl(): string
643
    {
644
        if ($this->data['type'] == 'image' && !Image::isSVG($this)) {
1✔
645
            return Image::getDataUrl($this, (int) $this->config->get('assets.images.quality'));
1✔
646
        }
647

648
        return \sprintf('data:%s;base64,%s', $this->data['subtype'], base64_encode($this->data['content']));
1✔
649
    }
650

651
    /**
652
     * Adds asset path to the list of assets to save.
653
     *
654
     * @throws RuntimeException
655
     */
656
    public function save(): void
657
    {
658
        if ($this->data['missing']) {
1✔
659
            return;
1✔
660
        }
661

662
        $cache = new Cache($this->builder, 'assets');
1✔
663
        if (!Util\File::getFS()->exists($cache->getContentFilePathname($this->data['path']))) {
1✔
NEW
664
            throw new RuntimeException(
×
NEW
665
                \sprintf('Can\'t add "%s" to assets list. Please clear cache and retry.', $this->data['path'])
×
NEW
666
            );
×
667
        }
668

669
        $this->builder->addAsset($this->data['path']);
1✔
670
    }
671

672
    /**
673
     * Is the asset an image and is it in CDN?
674
     */
675
    public function isImageInCdn(): bool
676
    {
677
        if (
678
            $this->data['type'] == 'image'
1✔
679
            && $this->config->isEnabled('assets.images.cdn')
1✔
680
            && $this->data['ext'] != 'ico'
1✔
681
            && (Image::isSVG($this) && $this->config->isEnabled('assets.images.cdn.svg'))
1✔
682
        ) {
NEW
683
            return true;
×
684
        }
685
        // handle remote image?
686
        if ($this->data['url'] !== null && $this->config->isEnabled('assets.images.cdn.remote')) {
1✔
NEW
687
            return true;
×
688
        }
689

690
        return false;
1✔
691
    }
692

693
    /**
694
     * Builds a relative path from a URL.
695
     * Used for remote files.
696
     */
697
    public static function buildPathFromUrl(string $url): string
698
    {
699
        $host = parse_url($url, PHP_URL_HOST);
1✔
700
        $path = parse_url($url, PHP_URL_PATH);
1✔
701
        $query = parse_url($url, PHP_URL_QUERY);
1✔
702
        $ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
1✔
703

704
        // Google Fonts hack
705
        if (Util\Str::endsWith($path, '/css') || Util\Str::endsWith($path, '/css2')) {
1✔
706
            $ext = 'css';
1✔
707
        }
708

709
        return Page::slugify(\sprintf('%s%s%s%s', $host, self::sanitize($path), $query ? "-$query" : '', $query && $ext ? ".$ext" : ''));
1✔
710
    }
711

712
    /**
713
     * Replaces some characters by '_'.
714
     */
715
    public static function sanitize(string $string): string
716
    {
717
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
1✔
718
    }
719

720
    /**
721
     * Returns local file path and updated path, or throw an exception.
722
     *
723
     * Try to locate the file in:
724
     *   (1. remote file)
725
     *   1. assets
726
     *   2. themes/<theme>/assets
727
     *   3. static
728
     *   4. themes/<theme>/static
729
     *
730
     * If $fallback is set, it will be used if the file is not found.
731
     *
732
     * @throws RuntimeException
733
     */
734
    private function locateFile(string $path, ?string $fallback = null): array
735
    {
736
        // remote file
737
        if (Util\File::isRemote($path)) {
1✔
738
            try {
739
                $content = $this->getRemoteFileContent($path);
1✔
740
                $path = self::buildPathFromUrl($path);
1✔
741
                $cache = new Cache($this->builder, 'assets/remote');
1✔
742
                if (!$cache->has($path)) {
1✔
743
                    $cache->set($path, [
1✔
744
                        'content' => $content,
1✔
745
                        'path'    => $path,
1✔
746
                    ], \DateInterval::createFromDateString('7 days'));
1✔
747
                }
748
                return [
1✔
749
                    'file' => $cache->getContentFilePathname($path),
1✔
750
                    'path' => $path,
1✔
751
                ];
1✔
752
            } catch (RuntimeException $e) {
1✔
753
                if ($fallback === null) {
1✔
NEW
754
                    throw new RuntimeException($e->getMessage(), previous: $e);
×
755
                }
756
                $path = $fallback;
1✔
757
            }
758
        }
759

760
        // checks in assets/
761
        $file = Util::joinFile($this->config->getAssetsPath(), $path);
1✔
762
        if (Util\File::getFS()->exists($file)) {
1✔
763
            return [
1✔
764
                'file' => $file,
1✔
765
                'path' => $path,
1✔
766
            ];
1✔
767
        }
768

769
        // checks in each themes/<theme>/assets/
770
        foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
771
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
1✔
772
            if (Util\File::getFS()->exists($file)) {
1✔
773
                return [
1✔
774
                    'file' => $file,
1✔
775
                    'path' => $path,
1✔
776
                ];
1✔
777
            }
778
        }
779

780
        // checks in static/
781
        $file = Util::joinFile($this->config->getStaticTargetPath(), $path);
1✔
782
        if (Util\File::getFS()->exists($file)) {
1✔
783
            return [
1✔
784
                'file' => $file,
1✔
785
                'path' => $path,
1✔
786
            ];
1✔
787
        }
788

789
        // checks in each themes/<theme>/static/
790
        foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
791
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
1✔
792
            if (Util\File::getFS()->exists($file)) {
1✔
793
                return [
1✔
794
                    'file' => $file,
1✔
795
                    'path' => $path,
1✔
796
                ];
1✔
797
            }
798
        }
799

800
        throw new RuntimeException(\sprintf('Can\'t locate file "%s".', $path));
1✔
801
    }
802

803
    /**
804
     * Try to get remote file content.
805
     * Returns file content or throw an exception.
806
     *
807
     * @throws RuntimeException
808
     */
809
    private function getRemoteFileContent(string $path): string
810
    {
811
        try {
812
            if (!Util\File::isRemoteExists($path)) {
1✔
813
                throw new RuntimeException(\sprintf('Remote file "%s" doesn\'t exists', $path));
1✔
814
            }
815
            if (false === $content = Util\File::fileGetContents($path, true)) {
1✔
NEW
816
                throw new RuntimeException(\sprintf('Can\'t get content of remote file "%s".', $path));
×
817
            }
818
            if (\strlen($content) <= 1) {
1✔
819
                throw new RuntimeException(\sprintf('Remote file "%s" is empty.', $path));
1✔
820
            }
821
        } catch (RuntimeException $e) {
1✔
822
            throw new RuntimeException($e->getMessage());
1✔
823
        }
824

825
        return $content;
1✔
826
    }
827

828
    /**
829
     * Returns the width of an image/SVG.
830
     *
831
     * @throws RuntimeException
832
     */
833
    private function getWidth(): int
834
    {
835
        if ($this->data['type'] != 'image') {
1✔
836
            return 0;
×
837
        }
838
        if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
1✔
839
            return (int) $svg->width;
1✔
840
        }
841
        if (false === $size = $this->getImageSize()) {
1✔
842
            throw new RuntimeException(\sprintf('Not able to get width of "%s".', $this->data['path']));
×
843
        }
844

845
        return $size[0];
1✔
846
    }
847

848
    /**
849
     * Returns the height of an image/SVG.
850
     *
851
     * @throws RuntimeException
852
     */
853
    private function getHeight(): int
854
    {
855
        if ($this->data['type'] != 'image') {
1✔
856
            return 0;
×
857
        }
858
        if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
1✔
859
            return (int) $svg->height;
1✔
860
        }
861
        if (false === $size = $this->getImageSize()) {
1✔
862
            throw new RuntimeException(\sprintf('Not able to get height of "%s".', $this->data['path']));
×
863
        }
864

865
        return $size[1];
1✔
866
    }
867

868
    /**
869
     * Returns image size informations.
870
     *
871
     * @see https://www.php.net/manual/function.getimagesize.php
872
     *
873
     * @return array|false
874
     */
875
    private function getImageSize()
876
    {
877
        if (!$this->data['type'] == 'image') {
1✔
878
            return false;
×
879
        }
880

881
        try {
882
            if (false === $size = getimagesizefromstring($this->data['content'])) {
1✔
883
                return false;
1✔
884
            }
885
        } catch (\Exception $e) {
×
886
            throw new RuntimeException(\sprintf('Handling asset "%s" failed: "%s"', $this->data['path'], $e->getMessage()));
×
887
        }
888

889
        return $size;
1✔
890
    }
891

892
    /**
893
     * Builds CDN image URL.
894
     */
895
    private function buildImageCdnUrl(): string
896
    {
897
        return str_replace(
×
898
            [
×
899
                '%account%',
×
900
                '%image_url%',
×
901
                '%width%',
×
902
                '%quality%',
×
903
                '%format%',
×
904
            ],
×
905
            [
×
NEW
906
                $this->config->get('assets.images.cdn.account') ?? '',
×
NEW
907
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical') ?? true]), '/'),
×
908
                $this->data['width'],
×
NEW
909
                (int) $this->config->get('assets.images.quality'),
×
910
                $this->data['ext'],
×
911
            ],
×
912
            (string) $this->config->get('assets.images.cdn.url')
×
913
        );
×
914
    }
915
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc