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

Cecilapp / Cecil / 13786562850

11 Mar 2025 11:08AM UTC coverage: 82.938% (-0.5%) from 83.394%
13786562850

push

github

web-flow
Merge pull request #2133 from Cecilapp/cache

feat: better cache and Twig cache fragments

106 of 124 new or added lines in 11 files covered. (85.48%)

23 existing lines in 6 files now uncovered.

2970 of 3581 relevant lines covered (82.94%)

0.83 hits per line

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

80.38
/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\Util;
23
use MatthiasMullie\Minify;
24
use ScssPhp\ScssPhp\Compiler;
25
use ScssPhp\ScssPhp\OutputStyle;
26
use wapmorgan\Mp3Info\Mp3Info;
27

28
class Asset implements \ArrayAccess
29
{
30
    /** @var Builder */
31
    protected $builder;
32

33
    /** @var Config */
34
    protected $config;
35

36
    /** @var array */
37
    protected $data = [];
38

39
    /** @var bool */
40
    protected $fingerprinted = false;
41

42
    /** @var bool */
43
    protected $compiled = false;
44

45
    /** @var bool */
46
    protected $minified = false;
47

48
    /** @var bool */
49
    protected $ignore_missing = false;
50

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

93
        // handles options
94
        $fingerprint = (bool) $this->config->get('assets.fingerprint.enabled');
1✔
95
        $minify = (bool) $this->config->get('assets.minify.enabled');
1✔
96
        $optimize = (bool) $this->config->get('assets.images.optimize.enabled');
1✔
97
        $filename = '';
1✔
98
        $ignore_missing = false;
1✔
99
        $remote_fallback = null;
1✔
100
        $force_slash = true;
1✔
101
        extract(\is_array($options) ? $options : [], EXTR_IF_EXISTS);
1✔
102

103
        // fill data array with file(s) informations
104
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
105
        $cacheKey = \sprintf('%s__%s', $filename ?: implode('_', $paths), $this->builder->getVersion());
1✔
106
        if (!$cache->has($cacheKey)) {
1✔
107
            $pathsCount = \count($paths);
1✔
108
            $file = [];
1✔
109
            for ($i = 0; $i < $pathsCount; $i++) {
1✔
110
                // loads file(s)
111
                $file[$i] = $this->loadFile($paths[$i], $ignore_missing, $remote_fallback, $force_slash);
1✔
112
                // bundle: same type only
113
                if ($i > 0) {
1✔
114
                    if ($file[$i]['type'] != $file[$i - 1]['type']) {
1✔
115
                        throw new RuntimeException(\sprintf('Asset bundle type error (%s != %s).', $file[$i]['type'], $file[$i - 1]['type']));
×
116
                    }
117
                }
118
                // missing allowed = empty path
119
                if ($file[$i]['missing']) {
1✔
120
                    $this->data['missing'] = true;
1✔
121
                    $this->data['path'] = $file[$i]['path'];
1✔
122

123
                    continue;
1✔
124
                }
125
                // set data
126
                $this->data['content'] .= $file[$i]['content'];
1✔
127
                $this->data['size'] += $file[$i]['size'];
1✔
128
                if ($i == 0) {
1✔
129
                    $this->data['file'] = $file[$i]['filepath'];
1✔
130
                    $this->data['filename'] = $file[$i]['path'];
1✔
131
                    $this->data['path'] = $file[$i]['path'];
1✔
132
                    $this->data['url'] = $file[$i]['url'];
1✔
133
                    $this->data['ext'] = $file[$i]['ext'];
1✔
134
                    $this->data['type'] = $file[$i]['type'];
1✔
135
                    $this->data['subtype'] = $file[$i]['subtype'];
1✔
136
                    // image: width, height and exif
137
                    if ($this->data['type'] == 'image') {
1✔
138
                        $this->data['width'] = $this->getWidth();
1✔
139
                        $this->data['height'] = $this->getHeight();
1✔
140
                        if ($this->data['subtype'] == 'image/jpeg') {
1✔
141
                            $this->data['exif'] = Util\File::readExif($file[$i]['filepath']);
1✔
142
                        }
143
                    }
144
                    // bundle default filename
145
                    if ($pathsCount > 1 && empty($filename)) {
1✔
146
                        switch ($this->data['ext']) {
1✔
147
                            case 'scss':
1✔
148
                            case 'css':
1✔
149
                                $filename = '/styles.css';
1✔
150
                                break;
1✔
151
                            case 'js':
1✔
152
                                $filename = '/scripts.js';
1✔
153
                                break;
1✔
154
                            default:
155
                                throw new RuntimeException(\sprintf('Asset bundle supports %s files only.', '.scss, .css and .js'));
×
156
                        }
157
                    }
158
                    // bundle filename and path
159
                    if (!empty($filename)) {
1✔
160
                        $this->data['filename'] = $filename;
1✔
161
                        $this->data['path'] = '/' . ltrim($filename, '/');
1✔
162
                    }
163
                }
164
                // bundle files path
165
                $this->data['files'][] = $file[$i]['filepath'];
1✔
166
            }
167
            // fingerprinting
168
            if ($fingerprint) {
1✔
NEW
169
                $this->fingerprint();
×
170
            }
171
            $cache->set($cacheKey, $this->data);
1✔
172
            $this->builder->getLogger()->debug(\sprintf('Asset created: "%s"', $this->data['path']));
1✔
173
            // optimizing images files
174
            if ($optimize && $this->data['type'] == 'image') {
1✔
175
                $this->optimize($cache->getContentFilePathname($this->data['path']), $this->data['path']);
1✔
176
            }
177
        }
178
        $this->data = $cache->get($cacheKey);
1✔
179
        // compiling (Sass files)
180
        if ((bool) $this->config->get('assets.compile.enabled')) {
1✔
181
            $this->compile();
1✔
182
        }
183
        // minifying (CSS and JavScript files)
184
        if ($minify) {
1✔
185
            $this->minify();
1✔
186
        }
187
    }
188

189
    /**
190
     * Returns path.
191
     *
192
     * @throws RuntimeException
193
     */
194
    public function __toString(): string
195
    {
196
        try {
197
            $this->save();
1✔
198
        } catch (RuntimeException $e) {
×
199
            $this->builder->getLogger()->error($e->getMessage());
×
200
        }
201

202
        if ($this->isImageInCdn()) {
1✔
203
            return $this->buildImageCdnUrl();
×
204
        }
205

206
        if ($this->builder->getConfig()->get('canonicalurl')) {
1✔
207
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
×
208
        }
209

210
        return $this->data['path'];
1✔
211
    }
212

213
    /**
214
     * Fingerprints a file.
215
     */
216
    public function fingerprint(): self
217
    {
218
        if ($this->fingerprinted) {
1✔
UNCOV
219
            return $this;
×
220
        }
221

222
        $fingerprint = hash('md5', $this->data['content']);
1✔
223
        $this->data['path'] = preg_replace(
1✔
224
            '/\.' . $this->data['ext'] . '$/m',
1✔
225
            ".$fingerprint." . $this->data['ext'],
1✔
226
            $this->data['path']
1✔
227
        );
1✔
228

229
        $this->fingerprinted = true;
1✔
230

231
        return $this;
1✔
232
    }
233

234
    /**
235
     * Compiles a SCSS.
236
     *
237
     * @throws RuntimeException
238
     */
239
    public function compile(): self
240
    {
241
        if ($this->compiled) {
1✔
242
            return $this;
1✔
243
        }
244

245
        if ($this->data['ext'] != 'scss') {
1✔
246
            return $this;
1✔
247
        }
248

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

319
        return $this;
1✔
320
    }
321

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

334
        if ($this->minified) {
1✔
335
            return $this;
×
336
        }
337

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

342
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
1✔
343
            return $this;
×
344
        }
345

346
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
1✔
NEW
347
            $this->minified = true;
×
348

349
            return $this;
×
350
        }
351

352
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
353
        $cacheKey = $cache->createKeyFromAsset($this, ['minified']);
1✔
354
        if (!$cache->has($cacheKey)) {
1✔
355
            switch ($this->data['ext']) {
1✔
356
                case 'css':
1✔
357
                    $minifier = new Minify\CSS($this->data['content']);
1✔
358
                    break;
1✔
359
                case 'js':
1✔
360
                    $minifier = new Minify\JS($this->data['content']);
1✔
361
                    break;
1✔
362
                default:
363
                    throw new RuntimeException(\sprintf('Not able to minify "%s".', $this->data['path']));
×
364
            }
365
            $this->data['path'] = preg_replace(
1✔
366
                '/\.' . $this->data['ext'] . '$/m',
1✔
367
                '.min.' . $this->data['ext'],
1✔
368
                $this->data['path']
1✔
369
            );
1✔
370
            $this->data['content'] = $minifier->minify();
1✔
371
            $this->data['size'] = \strlen($this->data['content']);
1✔
372
            $this->minified = true;
1✔
373
            $cache->set($cacheKey, $this->data);
1✔
374
            $this->builder->getLogger()->debug(\sprintf('Asset minified: "%s"', $this->data['path']));
1✔
375
        }
376
        $this->data = $cache->get($cacheKey);
1✔
377

378
        return $this;
1✔
379
    }
380

381
    /**
382
     * Optimizing $filepath image.
383
     * Returns the new file size.
384
     */
385
    public function optimize(string $filepath, string $path): int
386
    {
387
        $quality = $this->config->get('assets.images.quality');
1✔
388
        $message = \sprintf('Asset processed: "%s"', $path);
1✔
389
        $sizeBefore = filesize($filepath);
1✔
390
        Optimizer::create($quality)->optimize($filepath);
1✔
391
        $sizeAfter = filesize($filepath);
1✔
392
        if ($sizeAfter < $sizeBefore) {
1✔
393
            $message = \sprintf(
1✔
394
                'Asset optimized: "%s" (%s Ko -> %s Ko)',
1✔
395
                $path,
1✔
396
                ceil($sizeBefore / 1000),
1✔
397
                ceil($sizeAfter / 1000)
1✔
398
            );
1✔
399
        }
400
        $this->builder->getLogger()->debug($message);
1✔
401

402
        return $sizeAfter;
1✔
403
    }
404

405
    /**
406
     * Resizes an image with a new $width.
407
     *
408
     * @throws RuntimeException
409
     */
410
    public function resize(int $width): self
411
    {
412
        if ($this->data['missing']) {
1✔
413
            throw new RuntimeException(\sprintf('Not able to resize "%s": file not found.', $this->data['path']));
×
414
        }
415
        if ($this->data['type'] != 'image') {
1✔
416
            throw new RuntimeException(\sprintf('Not able to resize "%s": not an image.', $this->data['path']));
×
417
        }
418
        if ($width >= $this->data['width']) {
1✔
419
            return $this;
1✔
420
        }
421

422
        $assetResized = clone $this;
1✔
423
        $assetResized->data['width'] = $width;
1✔
424

425
        if ($this->isImageInCdn()) {
1✔
426
            return $assetResized; // returns asset with the new width only: CDN do the rest of the job
×
427
        }
428

429
        $quality = $this->config->get('assets.images.quality');
1✔
430
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
431
        $cacheKey = $cache->createKeyFromAsset($assetResized, ["{$width}x", "q$quality"]);
1✔
432
        if (!$cache->has($cacheKey)) {
1✔
433
            $assetResized->data['content'] = Image::resize($assetResized, $width, $quality);
1✔
434
            $assetResized->data['path'] = '/' . Util::joinPath(
1✔
435
                (string) $this->config->get('assets.target'),
1✔
436
                (string) $this->config->get('assets.images.resize.dir'),
1✔
437
                (string) $width,
1✔
438
                $assetResized->data['path']
1✔
439
            );
1✔
440
            $assetResized->data['height'] = $assetResized->getHeight();
1✔
441
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
1✔
442

443
            $cache->set($cacheKey, $assetResized->data);
1✔
444
            $this->builder->getLogger()->debug(\sprintf('Asset resized: "%s" (%sx)', $assetResized->data['path'], $width));
1✔
445
        }
446
        $assetResized->data = $cache->get($cacheKey);
1✔
447

448
        return $assetResized;
1✔
449
    }
450

451
    /**
452
     * Converts an image asset to $format format.
453
     *
454
     * @throws RuntimeException
455
     */
456
    public function convert(string $format, ?int $quality = null): self
457
    {
458
        if ($this->data['type'] != 'image') {
1✔
459
            throw new RuntimeException(\sprintf('Not able to convert "%s" (%s) to %s: not an image.', $this->data['path'], $this->data['type'], $format));
×
460
        }
461

462
        if ($quality === null) {
1✔
463
            $quality = (int) $this->config->get('assets.images.quality');
1✔
464
        }
465

466
        $asset = clone $this;
1✔
467
        $asset['ext'] = $format;
1✔
468

469
        if ($this->isImageInCdn()) {
1✔
470
            return $asset; // returns the asset with the new extension only: CDN do the rest of the job
×
471
        }
472

473
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
474
        $tags = ["q$quality"];
1✔
475
        if ($this->data['width']) {
1✔
476
            array_unshift($tags, "{$this->data['width']}x");
1✔
477
        }
478
        $cacheKey = $cache->createKeyFromAsset($asset, $tags);
1✔
479
        if (!$cache->has($cacheKey)) {
1✔
480
            $asset->data['content'] = Image::convert($asset, $format, $quality);
1✔
481
            $asset->data['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']);
1✔
482
            $asset->data['subtype'] = "image/$format";
1✔
483
            $asset->data['size'] = \strlen($asset->data['content']);
1✔
484
            $cache->set($cacheKey, $asset->data);
1✔
485
            $this->builder->getLogger()->debug(\sprintf('Asset converted: "%s" (%s -> %s)', $asset->data['path'], $this->data['ext'], $format));
1✔
486
        }
487
        $asset->data = $cache->get($cacheKey);
1✔
488

489
        return $asset;
1✔
490
    }
491

492
    /**
493
     * Converts an image asset to WebP format.
494
     *
495
     * @throws RuntimeException
496
     */
497
    public function webp(?int $quality = null): self
498
    {
499
        return $this->convert('webp', $quality);
1✔
500
    }
501

502
    /**
503
     * Converts an image asset to AVIF format.
504
     *
505
     * @throws RuntimeException
506
     */
507
    public function avif(?int $quality = null): self
508
    {
509
        return $this->convert('avif', $quality);
1✔
510
    }
511

512
    /**
513
     * Implements \ArrayAccess.
514
     */
515
    #[\ReturnTypeWillChange]
516
    public function offsetSet($offset, $value): void
517
    {
518
        if (!\is_null($offset)) {
1✔
519
            $this->data[$offset] = $value;
1✔
520
        }
521
    }
522

523
    /**
524
     * Implements \ArrayAccess.
525
     */
526
    #[\ReturnTypeWillChange]
527
    public function offsetExists($offset): bool
528
    {
529
        return isset($this->data[$offset]);
1✔
530
    }
531

532
    /**
533
     * Implements \ArrayAccess.
534
     */
535
    #[\ReturnTypeWillChange]
536
    public function offsetUnset($offset): void
537
    {
538
        unset($this->data[$offset]);
×
539
    }
540

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

550
    /**
551
     * Hashing content of an asset with the specified algo, sha384 by default.
552
     * Used for SRI (Subresource Integrity).
553
     *
554
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
555
     */
556
    public function getIntegrity(string $algo = 'sha384'): string
557
    {
558
        return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
1✔
559
    }
560

561
    /**
562
     * Returns MP3 file infos.
563
     *
564
     * @see https://github.com/wapmorgan/Mp3Info
565
     */
566
    public function getAudio(): Mp3Info
567
    {
568
        if ($this->data['type'] !== 'audio') {
1✔
569
            throw new RuntimeException(\sprintf('Not able to get audio infos of "%s".', $this->data['path']));
×
570
        }
571

572
        return new Mp3Info($this->data['file']);
1✔
573
    }
574

575
    /**
576
     * Returns MP4 file infos.
577
     *
578
     * @see https://github.com/clwu88/php-read-mp4info
579
     */
580
    public function getVideo(): array
581
    {
582
        if ($this->data['type'] !== 'video') {
1✔
583
            throw new RuntimeException(\sprintf('Not able to get video infos of "%s".', $this->data['path']));
×
584
        }
585

586
        return (array) \Clwu\Mp4::getInfo($this->data['file']);
1✔
587
    }
588

589
    /**
590
     * Returns the Data URL (encoded in Base64).
591
     *
592
     * @throws RuntimeException
593
     */
594
    public function dataurl(): string
595
    {
596
        if ($this->data['type'] == 'image' && !Image::isSVG($this)) {
1✔
597
            return Image::getDataUrl($this, $this->config->get('assets.images.quality'));
1✔
598
        }
599

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

603
    /**
604
     * Adds asset path to the list of assets to save.
605
     *
606
     * @throws RuntimeException
607
     */
608
    public function save(): void
609
    {
610
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
611
        if (Util\File::getFS()->exists($cache->getContentFilePathname($this->data['path']))) {
1✔
612
            $this->builder->addAsset($this->data['path']);
1✔
613
        }
614
    }
615

616
    /**
617
     * Is Asset is an image in CDN.
618
     *
619
     * @return bool
620
     */
621
    public function isImageInCdn()
622
    {
623
        if ($this->data['type'] != 'image' || (bool) $this->config->get('assets.images.cdn.enabled') !== true || (Image::isSVG($this) && (bool) $this->config->get('assets.images.cdn.svg') !== true)) {
1✔
624
            return false;
1✔
625
        }
626
        // remote image?
627
        if ($this->data['url'] !== null && (bool) $this->config->get('assets.images.cdn.remote') !== true) {
×
628
            return false;
×
629
        }
630

631
        return true;
×
632
    }
633

634
    /**
635
     * Load file data and store theme in $file array.
636
     *
637
     * @throws RuntimeException
638
     *
639
     * @return string[]
640
     */
641
    private function loadFile(string $path, bool $ignore_missing = false, ?string $remote_fallback = null, bool $force_slash = true): array
642
    {
643
        $file = [
1✔
644
            'url'      => null,
1✔
645
            'filepath' => null,
1✔
646
            'path'     => null,
1✔
647
            'ext'      => null,
1✔
648
            'type'     => null,
1✔
649
            'subtype'  => null,
1✔
650
            'size'     => null,
1✔
651
            'content'  => null,
1✔
652
            'missing'  => false,
1✔
653
        ];
1✔
654

655
        // try to find file locally and returns the file path
656
        try {
657
            $filePath = $this->locateFile($path, $remote_fallback);
1✔
658
        } catch (RuntimeException $e) {
1✔
659
            if ($ignore_missing) {
1✔
660
                $file['path'] = $path;
1✔
661
                $file['missing'] = true;
1✔
662

663
                return $file;
1✔
664
            }
665

666
            throw new RuntimeException(\sprintf('Can\'t load asset file "%s" (%s).', $path, $e->getMessage()));
×
667
        }
668

669
        // in case of an URL, update $path
670
        if (Util\Url::isUrl($path)) {
1✔
671
            $file['url'] = $path;
1✔
672
            $path = Util::joinPath(
1✔
673
                (string) $this->config->get('assets.target'),
1✔
674
                Util\File::getFS()->makePathRelative($filePath, $this->config->getAssetsRemotePath())
1✔
675
            );
1✔
676
            // trick: the `remote_fallback` file is in assets/ dir (not in cache/assets/remote/
677
            if (substr(Util\File::getFS()->makePathRelative($filePath, $this->config->getAssetsRemotePath()), 0, 2) == '..') {
1✔
678
                $path = Util::joinPath(
×
679
                    (string) $this->config->get('assets.target'),
×
680
                    Util\File::getFS()->makePathRelative($filePath, $this->config->getAssetsPath())
×
681
                );
×
682
            }
683
            $force_slash = true;
1✔
684
        }
685

686
        // force leading slash?
687
        if ($force_slash) {
1✔
688
            $path = '/' . ltrim($path, '/');
1✔
689
        }
690

691
        // get content and content type
692
        $content = Util\File::fileGetContents($filePath);
1✔
693
        list($type, $subtype) = Util\File::getMediaType($filePath);
1✔
694

695
        $file['filepath'] = $filePath;
1✔
696
        $file['path'] = $path;
1✔
697
        $file['ext'] = pathinfo($path)['extension'] ?? '';
1✔
698
        $file['type'] = $type;
1✔
699
        $file['subtype'] = $subtype;
1✔
700
        $file['size'] = filesize($filePath);
1✔
701
        $file['content'] = $content;
1✔
702
        $file['missing'] = false;
1✔
703

704
        return $file;
1✔
705
    }
706

707
    /**
708
     * Try to locate the file:
709
     *   1. remotely (if $path is a valid URL)
710
     *   2. in static|assets/
711
     *   3. in themes/<theme>/static|assets/
712
     * Returns local file path or throw an exception.
713
     *
714
     * @return string local file path
715
     *
716
     * @throws RuntimeException
717
     */
718
    private function locateFile(string $path, ?string $remote_fallback = null): string
719
    {
720
        // in case of a remote file: save it locally and returns its path
721
        if (Util\Url::isUrl($path)) {
1✔
722
            $url = $path;
1✔
723
            // create relative path
724
            $urlHost = parse_url($path, PHP_URL_HOST);
1✔
725
            $urlPath = parse_url($path, PHP_URL_PATH);
1✔
726
            $urlQuery = parse_url($path, PHP_URL_QUERY);
1✔
727
            $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
1✔
728
            // Google Fonts hack
729
            if (Util\Str::endsWith($urlPath, '/css') || Util\Str::endsWith($urlPath, '/css2')) {
1✔
730
                $extension = 'css';
1✔
731
            }
732
            $relativePath = Page::slugify(\sprintf(
1✔
733
                '%s%s%s%s',
1✔
734
                $urlHost,
1✔
735
                $this->sanitize($urlPath),
1✔
736
                $urlQuery ? "-$urlQuery" : '',
1✔
737
                $urlQuery && $extension ? ".$extension" : ''
1✔
738
            ));
1✔
739
            $filePath = Util::joinFile($this->config->getAssetsRemotePath(), $relativePath);
1✔
740
            // save file
741
            if (!file_exists($filePath)) {
1✔
742
                try {
743
                    // get content
744
                    if (!Util\Url::isRemoteFileExists($url)) {
1✔
745
                        throw new RuntimeException(\sprintf('File "%s" doesn\'t exists', $url));
×
746
                    }
747
                    if (false === $content = Util\File::fileGetContents($url, true)) {
1✔
748
                        throw new RuntimeException(\sprintf('Can\'t get content of file "%s".', $url));
×
749
                    }
750
                    if (\strlen($content) <= 1) {
1✔
751
                        throw new RuntimeException(\sprintf('File "%s" is empty.', $url));
1✔
752
                    }
753
                } catch (RuntimeException $e) {
×
754
                    // if there is a fallback in assets/ returns it
755
                    if ($remote_fallback) {
×
756
                        $filePath = Util::joinFile($this->config->getAssetsPath(), $remote_fallback);
×
757
                        if (Util\File::getFS()->exists($filePath)) {
×
758
                            return $filePath;
×
759
                        }
760

UNCOV
761
                        throw new RuntimeException(\sprintf('Fallback file "%s" doesn\'t exists.', $filePath));
×
762
                    }
763

764
                    throw new RuntimeException($e->getMessage());
×
765
                }
766
                Util\File::getFS()->dumpFile($filePath, $content);
1✔
767
            }
768

769
            return $filePath;
1✔
770
        }
771

772
        // checks in assets/
773
        $filePath = Util::joinFile($this->config->getAssetsPath(), $path);
1✔
774
        if (Util\File::getFS()->exists($filePath)) {
1✔
775
            return $filePath;
1✔
776
        }
777

778
        // checks in each themes/<theme>/assets/
779
        foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
780
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
1✔
781
            if (Util\File::getFS()->exists($filePath)) {
1✔
782
                return $filePath;
1✔
783
            }
784
        }
785

786
        // checks in static/
787
        $filePath = Util::joinFile($this->config->getStaticTargetPath(), $path);
1✔
788
        if (Util\File::getFS()->exists($filePath)) {
1✔
789
            return $filePath;
1✔
790
        }
791

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

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

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

820
        return $size[0];
1✔
821
    }
822

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

840
        return $size[1];
1✔
841
    }
842

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

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

864
        return $size;
1✔
865
    }
866

867
    /**
868
     * Replaces some characters by '_'.
869
     */
870
    private function sanitize(string $string): string
871
    {
872
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
1✔
873
    }
874

875
    /**
876
     * Builds CDN image URL.
877
     */
878
    private function buildImageCdnUrl(): string
879
    {
880
        return str_replace(
×
881
            [
×
882
                '%account%',
×
883
                '%image_url%',
×
884
                '%width%',
×
885
                '%quality%',
×
886
                '%format%',
×
887
            ],
×
888
            [
×
889
                $this->config->get('assets.images.cdn.account'),
×
890
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical')]), '/'),
×
891
                $this->data['width'],
×
892
                $this->config->get('assets.images.quality'),
×
893
                $this->data['ext'],
×
894
            ],
×
895
            (string) $this->config->get('assets.images.cdn.url')
×
896
        );
×
897
    }
898
}
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