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

Cecilapp / Cecil / 14620241211

23 Apr 2025 02:06PM UTC coverage: 83.787%. First build
14620241211

Pull #2148

github

web-flow
Merge 12fc09dec into 6d7ba8f0a
Pull Request #2148: refactor: configuration and cache

361 of 423 new or added lines in 26 files covered. (85.34%)

3049 of 3639 relevant lines covered (83.79%)

0.84 hits per line

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

83.05
/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 array Cache tags */
41
    protected $cacheTags = [];
42

43
    /**
44
     * Creates an Asset from a file path, an array of files path or an URL.
45
     * Options:
46
     * [
47
     *     'fingerprint' => <bool>,
48
     *     'minify' => <bool>,
49
     *     'optimize' => <bool>,
50
     *     'filename' => <string>,
51
     *     'ignore_missing' => <bool>,
52
     *     'fallback' => <string>,
53
     *     'leading_slash' => <bool>
54
     * ]
55
     *
56
     * @param Builder      $builder
57
     * @param string|array $paths
58
     * @param array|null   $options
59
     *
60
     * @throws RuntimeException
61
     */
62
    public function __construct(Builder $builder, string|array $paths, array|null $options = null)
63
    {
64
        $this->builder = $builder;
1✔
65
        $this->config = $builder->getConfig();
1✔
66
        $paths = \is_array($paths) ? $paths : [$paths];
1✔
67
        // checks path(s)
68
        array_walk($paths, function ($path) {
1✔
69
            // must be a string
70
            if (!\is_string($path)) {
1✔
71
                throw new RuntimeException(\sprintf('The path of an asset must be a string ("%s" given).', \gettype($path)));
×
72
            }
73
            // can't be empty
74
            if (empty($path)) {
1✔
75
                throw new RuntimeException('The path of an asset can\'t be empty.');
×
76
            }
77
            // can't be relative
78
            if (substr($path, 0, 2) == '..') {
1✔
NEW
79
                throw new RuntimeException(\sprintf('The path of asset "%s" is wrong: it must be directly relative to `assets` or `static` directory, or a remote URL.', $path));
×
80
            }
81
        });
1✔
82
        $this->data = [
1✔
83
            'file'     => '',    // absolute file path
1✔
84
            'files'    => [],    // array of absolute files path
1✔
85
            'path'     => '',    // public path
1✔
86
            '_path'    => '',    // original path
1✔
87
            'url'      => null,  // URL if it's a remote file
1✔
88
            'missing'  => false, // if file not found but missing allowed: 'missing' is true
1✔
89
            'ext'      => '',    // file extension
1✔
90
            'type'     => '',    // file type (e.g.: image, audio, video, etc.)
1✔
91
            'subtype'  => '',    // file media type (e.g.: image/png, audio/mp3, etc.)
1✔
92
            'size'     => 0,     // file size (in bytes)
1✔
93
            'width'    => 0,     // image width (in pixels)
1✔
94
            'height'   => 0,     // image height (in pixels)
1✔
95
            'exif'     => [],    // image exif data
1✔
96
            'content'  => '',    // file content
1✔
97
        ];
1✔
98

99
        // handles options
100
        $options = array_merge(
1✔
101
            [
1✔
102
                'fingerprint'    => $this->config->isEnabled('assets.fingerprint'),
1✔
103
                'minify'         => $this->config->isEnabled('assets.minify'),
1✔
104
                'optimize'       => $this->config->isEnabled('assets.images.optimize'),
1✔
105
                'filename'       => '',
1✔
106
                'ignore_missing' => false,
1✔
107
                'fallback'       => '',
1✔
108
                'leading_slash'  => true,
1✔
109
            ],
1✔
110
            \is_array($options) ? $options : []
1✔
111
        );
1✔
112

113
        // cache
114
        $cache = new Cache($this->builder, 'assets');
1✔
115
        $this->cacheTags = $options;
1✔
116
        $locateCacheKey = \sprintf('%s_locate__%s__%s', $options['filename'] ?: implode('_', $paths), $this->builder->getBuilId(), $this->builder->getVersion());
1✔
117

118
        // locate file(s) and get content
119
        if (!$cache->has($locateCacheKey)) {
1✔
120
            $pathsCount = \count($paths);
1✔
121
            for ($i = 0; $i < $pathsCount; $i++) {
1✔
122
                try {
123
                    $this->data['missing'] = false;
1✔
124
                    $locate = $this->locateFile($paths[$i], $options['fallback']);
1✔
125
                    $file = $locate['file'];
1✔
126
                    $path = $locate['path'];
1✔
127
                    $type = Util\File::getMediaType($file)[0];
1✔
128
                    if ($i > 0) { // bundle
1✔
129
                        if ($type != $this->data['type']) {
1✔
NEW
130
                            throw new RuntimeException(\sprintf('Asset bundle type error (%s != %s).', $type, $this->data['type']));
×
131
                        }
132
                    }
133
                    $this->data['file'] = $file;
1✔
134
                    $this->data['files'][] = $file;
1✔
135
                    $this->data['path'] = $path;
1✔
136
                    $this->data['url'] = Util\File::isRemote($paths[$i]) ? $paths[$i] : null;
1✔
137
                    $this->data['ext'] = Util\File::getExtension($file);
1✔
138
                    $this->data['type'] = $type;
1✔
139
                    $this->data['subtype'] = Util\File::getMediaType($file)[1];
1✔
140
                    $this->data['size'] += filesize($file);
1✔
141
                    $this->data['content'] .= Util\File::fileGetContents($file);
1✔
142
                    // bundle default filename
143
                    $filename = $options['filename'];
1✔
144
                    if ($pathsCount > 1 && empty($filename)) {
1✔
145
                        switch ($this->data['ext']) {
1✔
146
                            case 'scss':
1✔
147
                            case 'css':
1✔
148
                                $filename = 'styles.css';
1✔
149
                                break;
1✔
150
                            case 'js':
1✔
151
                                $filename = 'scripts.js';
1✔
152
                                break;
1✔
153
                            default:
154
                                throw new RuntimeException(\sprintf('Asset bundle supports %s files only.', '.scss, .css and .js'));
×
155
                        }
156
                    }
157
                    // apply bundle filename to path
158
                    if (!empty($filename)) {
1✔
159
                        $this->data['path'] = '/' . ltrim($filename, '/');
1✔
160
                    }
161
                    // force root slash
162
                    if ($options['leading_slash']) {
1✔
163
                        $this->data['path'] = '/' . ltrim($this->data['path'], '/');
1✔
164
                    }
165
                    $this->data['_path'] = $this->data['path'];
1✔
166
                } catch (RuntimeException $e) {
1✔
167
                    if ($options['ignore_missing']) {
1✔
168
                        $this->data['missing'] = true;
1✔
169
                        continue;
1✔
170
                    }
NEW
171
                    throw new RuntimeException(\sprintf('Can\'t handle asset "%s" (%s).', $paths[$i], $e->getMessage()));
×
172
                }
173
            }
174
            $cache->set($locateCacheKey, $this->data);
1✔
175
        }
176
        $this->data = $cache->get($locateCacheKey);
1✔
177

178
        // missing
179
        if ($this->data['missing']) {
1✔
180
            return;
1✔
181
        }
182

183
        // cache
184
        $cache = new Cache($this->builder, 'assets');
1✔
185
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
1✔
186
        if (!$cache->has($cacheKey)) {
1✔
187
            // image: width, height and exif
188
            if ($this->data['type'] == 'image') {
1✔
189
                $this->data['width'] = $this->getWidth();
1✔
190
                $this->data['height'] = $this->getHeight();
1✔
191
                if ($this->data['subtype'] == 'image/jpeg') {
1✔
192
                    $this->data['exif'] = Util\File::readExif($this->data['file']);
1✔
193
                }
194
            }
195
            // fingerprinting
196
            if ($options['fingerprint']) {
1✔
NEW
197
                $this->fingerprint();
×
198
            }
199
            // compiling Sass files
200
            $this->compile();
1✔
201
            // minifying (CSS and JavScript files)
202
            if ($options['minify']) {
1✔
203
                $this->minify();
1✔
204
            }
205
            $cache->set($cacheKey, $this->data);
1✔
206
            $this->builder->getLogger()->debug(\sprintf('Asset created: "%s"', $this->data['path']));
1✔
207
            // optimizing images files (in cache)
208
            if ($options['optimize'] && $this->data['type'] == 'image' && !$this->isImageInCdn()) {
1✔
209
                $this->optimize($cache->getContentFilePathname($this->data['path']), $this->data['path']);
1✔
210
            }
211
        }
212
        $this->data = $cache->get($cacheKey);
1✔
213
    }
214

215
    /**
216
     * Returns path.
217
     */
218
    public function __toString(): string
219
    {
220
        $this->save();
1✔
221

222
        if ($this->isImageInCdn()) {
1✔
223
            return $this->buildImageCdnUrl();
×
224
        }
225

226
        if ($this->builder->getConfig()->isEnabled('canonicalurl')) {
1✔
227
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
×
228
        }
229

230
        return $this->data['path'];
1✔
231
    }
232

233
    /**
234
     * Compiles a SCSS.
235
     *
236
     * @throws RuntimeException
237
     */
238
    public function compile(): self
239
    {
240
        if ($this->data['ext'] != 'scss') {
1✔
241
            return $this;
1✔
242
        }
243

244
        $cache = new Cache($this->builder, 'assets');
1✔
245

246
        $this->cacheTags['compile'] = true;
1✔
247

248
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
1✔
249
        if (!$cache->has($cacheKey)) {
1✔
250
            $scssPhp = new Compiler();
1✔
251
            // import paths
252
            $importDir = [];
1✔
253
            $importDir[] = Util::joinPath($this->config->getStaticPath());
1✔
254
            $importDir[] = Util::joinPath($this->config->getAssetsPath());
1✔
255
            $scssDir = (array) $this->config->get('assets.compile.import');
1✔
256
            $themes = $this->config->getTheme() ?? [];
1✔
257
            foreach ($scssDir as $dir) {
1✔
258
                $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir);
1✔
259
                $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir);
1✔
260
                $importDir[] = Util::joinPath(\dirname($this->data['file']), $dir);
1✔
261
                foreach ($themes as $theme) {
1✔
262
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir"));
1✔
263
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir"));
1✔
264
                }
265
            }
266
            $scssPhp->setQuietDeps(true);
1✔
267
            $scssPhp->setImportPaths(array_unique($importDir));
1✔
268
            // source map
269
            if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
1✔
270
                $importDir = [];
×
271
                $assetDir = (string) $this->config->get('assets.dir');
×
272
                $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR . $assetDir . DIRECTORY_SEPARATOR);
×
273
                $fileRelPath = substr($this->data['file'], $assetDirPos + 8);
×
274
                $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath);
×
275
                $importDir[] = \dirname($filePath);
×
276
                foreach ($scssDir as $dir) {
×
277
                    $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir);
×
278
                }
279
                $scssPhp->setImportPaths(array_unique($importDir));
×
280
                $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE);
×
281
                $scssPhp->setSourceMapOptions([
×
282
                    'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()),
×
283
                    'sourceRoot'        => '/',
×
284
                ]);
×
285
            }
286
            // output style
287
            $outputStyles = ['expanded', 'compressed'];
1✔
288
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
1✔
289
            if (!\in_array($outputStyle, $outputStyles)) {
1✔
290
                throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
×
291
            }
292
            $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
1✔
293
            // variables
294
            $variables = $this->config->get('assets.compile.variables');
1✔
295
            if (!empty($variables)) {
1✔
296
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
1✔
297
                $scssPhp->replaceVariables($variables);
1✔
298
            }
299
            // debug
300
            if ($this->builder->isDebug()) {
1✔
301
                $scssPhp->setQuietDeps(false);
1✔
302
                $this->builder->getLogger()->debug(\sprintf("SCSS compiler imported paths:\n%s", Util\Str::arrayToList(array_unique($importDir))));
1✔
303
            }
304
            // update data
305
            $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']);
1✔
306
            $this->data['ext'] = 'css';
1✔
307
            $this->data['type'] = 'text';
1✔
308
            $this->data['subtype'] = 'text/css';
1✔
309
            $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss();
1✔
310
            $this->data['size'] = \strlen($this->data['content']);
1✔
311
            $cache->set($cacheKey, $this->data);
1✔
312
            $this->builder->getLogger()->debug(\sprintf('Asset compiled: "%s"', $this->data['path']));
1✔
313
        }
314
        $this->data = $cache->get($cacheKey);
1✔
315

316
        return $this;
1✔
317
    }
318

319
    /**
320
     * Minifying a CSS or a JS.
321
     *
322
     * @throws RuntimeException
323
     */
324
    public function minify(): self
325
    {
326
        // in debug mode, disable minify to preserve inline source map
327
        if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
1✔
328
            return $this;
×
329
        }
330

331
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
1✔
332
            return $this;
×
333
        }
334

335
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
1✔
NEW
336
            return $this;
×
337
        }
338

339
        if ($this->data['ext'] == 'scss') {
1✔
NEW
340
            $this->compile();
×
341
        }
342

343
        $cache = new Cache($this->builder, 'assets');
1✔
344

345
        $this->cacheTags['minify'] = true;
1✔
346

347
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
1✔
348
        if (!$cache->has($cacheKey)) {
1✔
349
            switch ($this->data['ext']) {
1✔
350
                case 'css':
1✔
351
                    $minifier = new Minify\CSS($this->data['content']);
1✔
352
                    break;
1✔
353
                case 'js':
1✔
354
                    $minifier = new Minify\JS($this->data['content']);
1✔
355
                    break;
1✔
356
                default:
357
                    throw new RuntimeException(\sprintf('Not able to minify "%s".', $this->data['path']));
×
358
            }
359
            $this->data['content'] = $minifier->minify();
1✔
360
            $this->data['size'] = \strlen($this->data['content']);
1✔
361
            $cache->set($cacheKey, $this->data);
1✔
362
            $this->builder->getLogger()->debug(\sprintf('Asset minified: "%s"', $this->data['path']));
1✔
363
        }
364
        $this->data = $cache->get($cacheKey);
1✔
365

366
        return $this;
1✔
367
    }
368

369
    /**
370
     * Add hash to the file name.
371
     */
372
    public function fingerprint(): self
373
    {
374
        $cache = new Cache($this->builder, 'assets');
1✔
375

376
        $this->cacheTags['fingerprint'] = true;
1✔
377

378
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
1✔
379
        if (!$cache->has($cacheKey)) {
1✔
380
            $hash = hash('md5', $this->data['content']);
1✔
381
            $this->data['path'] = preg_replace(
1✔
382
                '/\.' . $this->data['ext'] . '$/m',
1✔
383
                ".$hash." . $this->data['ext'],
1✔
384
                $this->data['path']
1✔
385
            );
1✔
386
            $cache->set($cacheKey, $this->data);
1✔
387
            $this->builder->getLogger()->debug(\sprintf('Asset fingerprinted: "%s"', $this->data['path']));
1✔
388
        }
389
        $this->data = $cache->get($cacheKey);
1✔
390

391
        return $this;
1✔
392
    }
393

394
    /**
395
     * Optimizing $filepath image.
396
     * Returns the new file size.
397
     */
398
    public function optimize(string $filepath, string $path): int
399
    {
400
        $quality = (int) $this->config->get('assets.images.quality');
1✔
401
        $message = \sprintf('Asset processed: "%s"', $path);
1✔
402
        $sizeBefore = filesize($filepath);
1✔
403
        Optimizer::create($quality)->optimize($filepath);
1✔
404
        $sizeAfter = filesize($filepath);
1✔
405
        if ($sizeAfter < $sizeBefore) {
1✔
406
            $message = \sprintf(
1✔
407
                'Asset optimized: "%s" (%s Ko -> %s Ko)',
1✔
408
                $path,
1✔
409
                ceil($sizeBefore / 1000),
1✔
410
                ceil($sizeAfter / 1000)
1✔
411
            );
1✔
412
        }
413
        $this->builder->getLogger()->debug($message);
1✔
414

415
        return $sizeAfter;
1✔
416
    }
417

418
    /**
419
     * Resizes an image with a new $width.
420
     *
421
     * @throws RuntimeException
422
     */
423
    public function resize(int $width): self
424
    {
425
        if ($this->data['missing']) {
1✔
426
            throw new RuntimeException(\sprintf('Not able to resize "%s": file not found.', $this->data['path']));
×
427
        }
428
        if ($this->data['type'] != 'image') {
1✔
429
            throw new RuntimeException(\sprintf('Not able to resize "%s": not an image.', $this->data['path']));
×
430
        }
431
        if ($width >= $this->data['width']) {
1✔
432
            return $this;
1✔
433
        }
434

435
        $assetResized = clone $this;
1✔
436
        $assetResized->data['width'] = $width;
1✔
437

438
        if ($this->isImageInCdn()) {
1✔
439
            $assetResized->data['height'] = round($this->data['height'] / ($this->data['width'] / $width));
×
440

441
            return $assetResized; // returns asset with the new dimensions only: CDN do the rest of the job
×
442
        }
443

444
        $quality = (int) $this->config->get('assets.images.quality');
1✔
445

446
        $cache = new Cache($this->builder, 'assets');
1✔
447
        $this->cacheTags['quality'] = $quality;
1✔
448
        $this->cacheTags['width'] = $width;
1✔
449
        $cacheKey = $cache->createKeyFromAsset($assetResized, $this->cacheTags);
1✔
450
        if (!$cache->has($cacheKey)) {
1✔
451
            $assetResized->data['content'] = Image::resize($assetResized, $width, $quality);
1✔
452
            $assetResized->data['path'] = '/' . Util::joinPath(
1✔
453
                (string) $this->config->get('assets.target'),
1✔
454
                'thumbnails',
1✔
455
                (string) $width,
1✔
456
                $assetResized->data['path']
1✔
457
            );
1✔
458
            $assetResized->data['height'] = $assetResized->getHeight();
1✔
459
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
1✔
460

461
            $cache->set($cacheKey, $assetResized->data);
1✔
462
            $this->builder->getLogger()->debug(\sprintf('Asset resized: "%s" (%sx)', $assetResized->data['path'], $width));
1✔
463
        }
464
        $assetResized->data = $cache->get($cacheKey);
1✔
465

466
        return $assetResized;
1✔
467
    }
468

469
    /**
470
     * Converts an image asset to $format format.
471
     *
472
     * @throws RuntimeException
473
     */
474
    public function convert(string $format, ?int $quality = null): self
475
    {
476
        if ($this->data['type'] != 'image') {
1✔
477
            throw new RuntimeException(\sprintf('Not able to convert "%s" (%s) to %s: not an image.', $this->data['path'], $this->data['type'], $format));
×
478
        }
479

480
        if ($quality === null) {
1✔
481
            $quality = (int) $this->config->get('assets.images.quality');
1✔
482
        }
483

484
        $asset = clone $this;
1✔
485
        $asset['ext'] = $format;
1✔
486
        $asset->data['subtype'] = "image/$format";
1✔
487

488
        if ($this->isImageInCdn()) {
1✔
489
            return $asset; // returns the asset with the new extension only: CDN do the rest of the job
×
490
        }
491

492
        $cache = new Cache($this->builder, 'assets');
1✔
493
        $this->cacheTags['quality'] = $quality;
1✔
494
        if ($this->data['width']) {
1✔
495
            $this->cacheTags['width'] = $this->data['width'];
1✔
496
        }
497
        $cacheKey = $cache->createKeyFromAsset($asset, $this->cacheTags);
1✔
498
        if (!$cache->has($cacheKey)) {
1✔
499
            $asset->data['content'] = Image::convert($asset, $format, $quality);
1✔
500
            $asset->data['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']);
1✔
501
            $asset->data['size'] = \strlen($asset->data['content']);
1✔
502
            $cache->set($cacheKey, $asset->data);
1✔
503
            $this->builder->getLogger()->debug(\sprintf('Asset converted: "%s" (%s -> %s)', $asset->data['path'], $this->data['ext'], $format));
1✔
504
        }
505
        $asset->data = $cache->get($cacheKey);
1✔
506

507
        return $asset;
1✔
508
    }
509

510
    /**
511
     * Converts an image asset to WebP format.
512
     *
513
     * @throws RuntimeException
514
     */
515
    public function webp(?int $quality = null): self
516
    {
517
        return $this->convert('webp', $quality);
1✔
518
    }
519

520
    /**
521
     * Converts an image asset to AVIF format.
522
     *
523
     * @throws RuntimeException
524
     */
525
    public function avif(?int $quality = null): self
526
    {
527
        return $this->convert('avif', $quality);
1✔
528
    }
529

530
    /**
531
     * Implements \ArrayAccess.
532
     */
533
    #[\ReturnTypeWillChange]
534
    public function offsetSet($offset, $value): void
535
    {
536
        if (!\is_null($offset)) {
1✔
537
            $this->data[$offset] = $value;
1✔
538
        }
539
    }
540

541
    /**
542
     * Implements \ArrayAccess.
543
     */
544
    #[\ReturnTypeWillChange]
545
    public function offsetExists($offset): bool
546
    {
547
        return isset($this->data[$offset]);
1✔
548
    }
549

550
    /**
551
     * Implements \ArrayAccess.
552
     */
553
    #[\ReturnTypeWillChange]
554
    public function offsetUnset($offset): void
555
    {
556
        unset($this->data[$offset]);
×
557
    }
558

559
    /**
560
     * Implements \ArrayAccess.
561
     */
562
    #[\ReturnTypeWillChange]
563
    public function offsetGet($offset)
564
    {
565
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
1✔
566
    }
567

568
    /**
569
     * Hashing content of an asset with the specified algo, sha384 by default.
570
     * Used for SRI (Subresource Integrity).
571
     *
572
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
573
     */
574
    public function getIntegrity(string $algo = 'sha384'): string
575
    {
576
        return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
1✔
577
    }
578

579
    /**
580
     * Returns MP3 file infos.
581
     *
582
     * @see https://github.com/wapmorgan/Mp3Info
583
     */
584
    public function getAudio(): Mp3Info
585
    {
586
        if ($this->data['type'] !== 'audio') {
1✔
587
            throw new RuntimeException(\sprintf('Not able to get audio infos of "%s".', $this->data['path']));
×
588
        }
589

590
        return new Mp3Info($this->data['file']);
1✔
591
    }
592

593
    /**
594
     * Returns MP4 file infos.
595
     *
596
     * @see https://github.com/clwu88/php-read-mp4info
597
     */
598
    public function getVideo(): array
599
    {
600
        if ($this->data['type'] !== 'video') {
1✔
601
            throw new RuntimeException(\sprintf('Not able to get video infos of "%s".', $this->data['path']));
×
602
        }
603

604
        return (array) \Clwu\Mp4::getInfo($this->data['file']);
1✔
605
    }
606

607
    /**
608
     * Returns the Data URL (encoded in Base64).
609
     *
610
     * @throws RuntimeException
611
     */
612
    public function dataurl(): string
613
    {
614
        if ($this->data['type'] == 'image' && !Image::isSVG($this)) {
1✔
615
            return Image::getDataUrl($this, (int) $this->config->get('assets.images.quality'));
1✔
616
        }
617

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

621
    /**
622
     * Adds asset path to the list of assets to save.
623
     *
624
     * @throws RuntimeException
625
     */
626
    public function save(): void
627
    {
628
        if ($this->data['missing']) {
1✔
629
            return;
1✔
630
        }
631

632
        $cache = new Cache($this->builder, 'assets');
1✔
633
        if (!Util\File::getFS()->exists($cache->getContentFilePathname($this->data['path']))) {
1✔
NEW
634
            throw new RuntimeException(
×
NEW
635
                \sprintf('Can\'t add "%s" to assets list. Please clear cache and retry.', $this->data['path'])
×
NEW
636
            );
×
637
        }
638

639
        $this->builder->addAsset($this->data['path']);
1✔
640
    }
641

642
    /**
643
     * Is the asset an image and is it in CDN?
644
     */
645
    public function isImageInCdn(): bool
646
    {
647
        if (
648
            $this->data['type'] == 'image'
1✔
649
            && $this->config->isEnabled('assets.images.cdn')
1✔
650
            && $this->data['ext'] != 'ico'
1✔
651
            && (Image::isSVG($this) && $this->config->isEnabled('assets.images.cdn.svg'))
1✔
652
        ) {
NEW
653
            return true;
×
654
        }
655
        // handle remote image?
656
        if ($this->data['url'] !== null && $this->config->isEnabled('assets.images.cdn.remote')) {
1✔
NEW
657
            return true;
×
658
        }
659

660
        return false;
1✔
661
    }
662

663
    /**
664
     * Builds a relative path from a URL.
665
     * Used for remote files.
666
     */
667
    public static function buildPathFromUrl(string $url): string
668
    {
669
        $host = parse_url($url, PHP_URL_HOST);
1✔
670
        $path = parse_url($url, PHP_URL_PATH);
1✔
671
        $query = parse_url($url, PHP_URL_QUERY);
1✔
672
        $ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
1✔
673

674
        // Google Fonts hack
675
        if (Util\Str::endsWith($path, '/css') || Util\Str::endsWith($path, '/css2')) {
1✔
676
            $ext = 'css';
1✔
677
        }
678

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

682
    /**
683
     * Replaces some characters by '_'.
684
     */
685
    public static function sanitize(string $string): string
686
    {
687
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
1✔
688
    }
689

690
    /**
691
     * Returns local file path and updated path, or throw an exception.
692
     *
693
     * Try to locate the file in:
694
     *   (1. remote file)
695
     *   1. assets
696
     *   2. themes/<theme>/assets
697
     *   3. static
698
     *   4. themes/<theme>/static
699
     *
700
     * If $fallback is set, it will be used if the file is not found.
701
     *
702
     * @throws RuntimeException
703
     */
704
    private function locateFile(string $path, ?string $fallback = null): array
705
    {
706
        // remote file
707
        if (Util\File::isRemote($path)) {
1✔
708
            try {
709
                $content = $this->getRemoteFileContent($path);
1✔
710
                $path = self::buildPathFromUrl($path);
1✔
711
                $cache = new Cache($this->builder, 'assets/remote');
1✔
712
                if (!$cache->has($path)) {
1✔
713
                    $cache->set($path, [
1✔
714
                        'content' => $content,
1✔
715
                        'path'    => $path,
1✔
716
                    ], \DateInterval::createFromDateString('7 days'));
1✔
717
                }
718
                return [
1✔
719
                    'file' => $cache->getContentFilePathname($path),
1✔
720
                    'path' => $path,
1✔
721
                ];
1✔
722
            } catch (RuntimeException $e) {
1✔
723
                if ($fallback === null) {
1✔
NEW
724
                    throw new RuntimeException($e->getMessage(), previous: $e);
×
725
                }
726
                $path = $fallback;
1✔
727
            }
728
        }
729

730
        // checks in assets/
731
        $file = Util::joinFile($this->config->getAssetsPath(), $path);
1✔
732
        if (Util\File::getFS()->exists($file)) {
1✔
733
            return [
1✔
734
                'file' => $file,
1✔
735
                'path' => $path,
1✔
736
            ];
1✔
737
        }
738

739
        // checks in each themes/<theme>/assets/
740
        foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
741
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
1✔
742
            if (Util\File::getFS()->exists($file)) {
1✔
743
                return [
1✔
744
                    'file' => $file,
1✔
745
                    'path' => $path,
1✔
746
                ];
1✔
747
            }
748
        }
749

750
        // checks in static/
751
        $file = Util::joinFile($this->config->getStaticTargetPath(), $path);
1✔
752
        if (Util\File::getFS()->exists($file)) {
1✔
753
            return [
1✔
754
                'file' => $file,
1✔
755
                'path' => $path,
1✔
756
            ];
1✔
757
        }
758

759
        // checks in each themes/<theme>/static/
760
        foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
761
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $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

770
        throw new RuntimeException(\sprintf('Can\'t locate file "%s".', $path));
1✔
771
    }
772

773
    /**
774
     * Try to get remote file content.
775
     * Returns file content or throw an exception.
776
     *
777
     * @throws RuntimeException
778
     */
779
    private function getRemoteFileContent(string $path): string
780
    {
781
        try {
782
            if (!Util\File::isRemoteExists($path)) {
1✔
783
                throw new RuntimeException(\sprintf('Remote file "%s" doesn\'t exists', $path));
1✔
784
            }
785
            if (false === $content = Util\File::fileGetContents($path, true)) {
1✔
NEW
786
                throw new RuntimeException(\sprintf('Can\'t get content of remote file "%s".', $path));
×
787
            }
788
            if (\strlen($content) <= 1) {
1✔
789
                throw new RuntimeException(\sprintf('Remote file "%s" is empty.', $path));
1✔
790
            }
791
        } catch (RuntimeException $e) {
1✔
792
            throw new RuntimeException($e->getMessage());
1✔
793
        }
794

795
        return $content;
1✔
796
    }
797

798
    /**
799
     * Returns the width of an image/SVG.
800
     *
801
     * @throws RuntimeException
802
     */
803
    private function getWidth(): int
804
    {
805
        if ($this->data['type'] != 'image') {
1✔
806
            return 0;
×
807
        }
808
        if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
1✔
809
            return (int) $svg->width;
1✔
810
        }
811
        if (false === $size = $this->getImageSize()) {
1✔
812
            throw new RuntimeException(\sprintf('Not able to get width of "%s".', $this->data['path']));
×
813
        }
814

815
        return $size[0];
1✔
816
    }
817

818
    /**
819
     * Returns the height of an image/SVG.
820
     *
821
     * @throws RuntimeException
822
     */
823
    private function getHeight(): int
824
    {
825
        if ($this->data['type'] != 'image') {
1✔
826
            return 0;
×
827
        }
828
        if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
1✔
829
            return (int) $svg->height;
1✔
830
        }
831
        if (false === $size = $this->getImageSize()) {
1✔
832
            throw new RuntimeException(\sprintf('Not able to get height of "%s".', $this->data['path']));
×
833
        }
834

835
        return $size[1];
1✔
836
    }
837

838
    /**
839
     * Returns image size informations.
840
     *
841
     * @see https://www.php.net/manual/function.getimagesize.php
842
     *
843
     * @return array|false
844
     */
845
    private function getImageSize()
846
    {
847
        if (!$this->data['type'] == 'image') {
1✔
848
            return false;
×
849
        }
850

851
        try {
852
            if (false === $size = getimagesizefromstring($this->data['content'])) {
1✔
853
                return false;
1✔
854
            }
855
        } catch (\Exception $e) {
×
856
            throw new RuntimeException(\sprintf('Handling asset "%s" failed: "%s"', $this->data['path'], $e->getMessage()));
×
857
        }
858

859
        return $size;
1✔
860
    }
861

862
    /**
863
     * Builds CDN image URL.
864
     */
865
    private function buildImageCdnUrl(): string
866
    {
867
        return str_replace(
×
868
            [
×
869
                '%account%',
×
870
                '%image_url%',
×
871
                '%width%',
×
872
                '%quality%',
×
873
                '%format%',
×
874
            ],
×
875
            [
×
NEW
876
                $this->config->get('assets.images.cdn.account') ?? '',
×
NEW
877
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical') ?? true]), '/'),
×
878
                $this->data['width'],
×
NEW
879
                (int) $this->config->get('assets.images.quality'),
×
880
                $this->data['ext'],
×
881
            ],
×
882
            (string) $this->config->get('assets.images.cdn.url')
×
883
        );
×
884
    }
885
}
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