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

Cecilapp / Cecil / 24640306665

19 Apr 2026 10:08PM UTC coverage: 82.306% (-0.1%) from 82.415%
24640306665

push

github

web-flow
Localize Markdown image assets for translated pages, document behavior, and harden cache pruning shard mapping (#2353)

79 of 100 new or added lines in 6 files covered. (79.0%)

3405 of 4137 relevant lines covered (82.31%)

0.82 hits per line

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

77.97
/src/Asset.php
1
<?php
2

3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <arnaud@ligny.fr>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
declare(strict_types=1);
13

14
namespace Cecil;
15

16
use Cecil\Asset\Image;
17
use Cecil\Builder;
18
use Cecil\Cache;
19
use Cecil\Collection\Page\Page;
20
use Cecil\Config;
21
use Cecil\Exception\ConfigException;
22
use Cecil\Exception\RuntimeException;
23
use Cecil\Url;
24
use Cecil\Util;
25
use Cecil\Util\ImageOptimizer as Optimizer;
26
use MatthiasMullie\Minify;
27
use ScssPhp\ScssPhp\Compiler;
28
use ScssPhp\ScssPhp\OutputStyle;
29
use wapmorgan\Mp3Info\Mp3Info;
30

31
/**
32
 * Asset class.
33
 *
34
 * Represents an asset (file) in the Cecil project.
35
 * Handles file locating, content reading, compiling, minifying, fingerprinting,
36
 * resizing images, and more.
37
 */
38
class Asset implements \ArrayAccess
39
{
40
    public const IMAGE_THUMB = 'thumbnails';
41

42
    /** @var Builder */
43
    protected $builder;
44

45
    /** @var Config */
46
    protected $config;
47

48
    /** @var array */
49
    protected $data = [];
50

51
    /** @var array Cache tags */
52
    protected $cacheTags = [];
53

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

113
        // handles options
114
        $options = array_merge(
1✔
115
            [
1✔
116
                'filename'       => '',
1✔
117
                'ignore_missing' => false,
1✔
118
                'fingerprint'    => $this->config->isEnabled('assets.fingerprint'),
1✔
119
                'minify'         => $this->config->isEnabled('assets.minify'),
1✔
120
                'optimize'       => $this->config->isEnabled('assets.images.optimize'),
1✔
121
                'fallback'       => '',
1✔
122
                'useragent'      => (string) $this->config->get('assets.remote.useragent.default'),
1✔
123
                'language'       => null,
1✔
124
            ],
1✔
125
            \is_array($options) ? $options : []
1✔
126
        );
1✔
127
        $language = null;
1✔
128
        if (isset($options['language']) && \is_scalar($options['language'])) {
1✔
129
            $language = (string) $options['language'];
1✔
130
            $language = $language === '' ? null : $language;
1✔
131
        }
132
        unset($options['language']);
1✔
133

134
        // cache for "locate file(s)"
135
        $cache = new Cache($this->builder, 'assets');
1✔
136
        $locateCacheKey = \sprintf(
1✔
137
            '%s_locate%s__%s__%s',
1✔
138
            $options['filename'] ?: implode('_', $paths),
1✔
139
            $language ? '_' . $language : '',
1✔
140
            Builder::getBuildId(),
1✔
141
            Builder::getVersion()
1✔
142
        );
1✔
143

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

208
        // missing
209
        if ($this->isMissing()) {
1✔
210
            return;
1✔
211
        }
212

213
        // cache for "process asset"
214
        $cache = new Cache($this->builder, 'assets');
1✔
215
        // create cache tags from options
216
        $this->cacheTags = $options;
1✔
217
        // remove unnecessary cache tags
218
        unset($this->cacheTags['optimize'], $this->cacheTags['ignore_missing'], $this->cacheTags['fallback'], $this->cacheTags['useragent']);
1✔
219
        if (!\in_array($this->data['ext'], ['css', 'js', 'scss'])) {
1✔
220
            unset($this->cacheTags['minify']);
1✔
221
        }
222
        // optimize image?
223
        $optimize = false;
1✔
224
        if ($options['optimize'] && $this->data['type'] == 'image' && !$this->isImageInCdn()) {
1✔
225
            $optimize = true;
1✔
226
            $quality = (int) $this->config->get('assets.images.quality');
1✔
227
            $this->cacheTags['quality'] = $quality;
1✔
228
        }
229
        $cacheKey = $cache->createKey($this, tags: $this->cacheTags);
1✔
230
        if (!$cache->has($cacheKey)) {
1✔
231
            // fingerprinting
232
            if ($options['fingerprint']) {
1✔
233
                $this->doFingerprint();
×
234
            }
235
            // compiling Sass files
236
            $this->doCompile();
1✔
237
            // minifying (CSS and JavaScript files)
238
            if ($options['minify']) {
1✔
239
                $this->doMinify();
×
240
            }
241
            // get width and height
242
            $this->data['width'] = $this->getWidth();
1✔
243
            $this->data['height'] = $this->getHeight();
1✔
244
            // get image exif
245
            if ($this->data['subtype'] == 'image/jpeg') {
1✔
246
                $this->data['exif'] = Util\File::readExif($this->data['file']);
1✔
247
            }
248
            // get duration
249
            if ($this->data['type'] == 'audio') {
1✔
250
                $this->data['duration'] = $this->getAudio()['duration'];
1✔
251
            }
252
            if ($this->data['type'] == 'video') {
1✔
253
                $this->data['duration'] = $this->getVideo()['duration'];
1✔
254
            }
255
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
1✔
256
            $this->builder->getLogger()->debug(\sprintf('Asset cached: "%s"', $this->data['path']));
1✔
257
            // optimizing images files (in cache directory)
258
            if ($optimize) {
1✔
259
                $this->optimizeImage($cache->getContentFile($this->data['path']), $this->data['path'], $quality);
1✔
260
            }
261
        }
262
        $this->data = $cache->get($cacheKey);
1✔
263
    }
264

265
    /**
266
     * Returns path.
267
     */
268
    public function __toString(): string
269
    {
270
        $this->save();
1✔
271

272
        if ($this->isImageInCdn()) {
1✔
273
            return $this->buildImageCdnUrl();
×
274
        }
275

276
        if ($this->builder->getConfig()->isEnabled('canonicalurl')) {
1✔
277
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
×
278
        }
279

280
        return $this->data['path'];
1✔
281
    }
282

283
    /**
284
     * Implements \ArrayAccess.
285
     */
286
    #[\ReturnTypeWillChange]
287
    public function offsetSet($offset, $value): void
288
    {
289
        if (!\is_null($offset)) {
1✔
290
            $this->data[$offset] = $value;
1✔
291
        }
292
    }
293

294
    /**
295
     * Implements \ArrayAccess.
296
     */
297
    #[\ReturnTypeWillChange]
298
    public function offsetExists($offset): bool
299
    {
300
        return isset($this->data[$offset]);
1✔
301
    }
302

303
    /**
304
     * Implements \ArrayAccess.
305
     */
306
    #[\ReturnTypeWillChange]
307
    public function offsetUnset($offset): void
308
    {
309
        unset($this->data[$offset]);
×
310
    }
311

312
    /**
313
     * Implements \ArrayAccess.
314
     */
315
    #[\ReturnTypeWillChange]
316
    public function offsetGet($offset)
317
    {
318
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
1✔
319
    }
320

321
    /**
322
     * Saves the asset by adding its path to the build assets list.
323
     * Skips assets marked as missing and validates that the asset file exists in cache before adding it.
324
     *
325
     * @throws RuntimeException
326
     */
327
    public function save(): void
328
    {
329
        if ($this->isMissing()) {
1✔
330
            return;
1✔
331
        }
332

333
        $cache = new Cache($this->builder, 'assets');
1✔
334
        if (empty($this->data['path']) || !Util\File::getFS()->exists($cache->getContentFile($this->data['path']))) {
1✔
335
            throw new RuntimeException(\sprintf('Unable to add "%s" to assets list. Please clear cache and retry.', $this->data['path']));
×
336
        }
337

338
        $this->builder->addToAssetsList($this->data['path']);
1✔
339
    }
340

341
    /**
342
     * Checks if the asset is missing.
343
     */
344
    public function isMissing(): bool
345
    {
346
        return $this->data['missing'];
1✔
347
    }
348

349
    /**
350
     * Add hash to the file name + cache.
351
     */
352
    public function fingerprint(): self
353
    {
354
        $this->cacheTags['fingerprint'] = true;
1✔
355
        $cache = new Cache($this->builder, 'assets');
1✔
356
        $cacheKey = $cache->createKey($this, tags: $this->cacheTags);
1✔
357
        if (!$cache->has($cacheKey)) {
1✔
358
            $this->doFingerprint();
1✔
359
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
1✔
360
        }
361
        $this->data = $cache->get($cacheKey);
1✔
362

363
        return $this;
1✔
364
    }
365

366
    /**
367
     * Compiles a SCSS + cache.
368
     *
369
     * @throws RuntimeException
370
     */
371
    public function compile(): self
372
    {
373
        $this->cacheTags['compile'] = true;
1✔
374
        $cache = new Cache($this->builder, 'assets');
1✔
375
        $cacheKey = $cache->createKey($this, tags: $this->cacheTags);
1✔
376
        if (!$cache->has($cacheKey)) {
1✔
377
            $this->doCompile();
1✔
378
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
1✔
379
        }
380
        $this->data = $cache->get($cacheKey);
1✔
381

382
        return $this;
1✔
383
    }
384

385
    /**
386
     * Minifying a CSS or a JS.
387
     */
388
    public function minify(): self
389
    {
390
        $this->cacheTags['minify'] = true;
1✔
391
        $cache = new Cache($this->builder, 'assets');
1✔
392
        $cacheKey = $cache->createKey($this, tags: $this->cacheTags);
1✔
393
        if (!$cache->has($cacheKey)) {
1✔
394
            $this->doMinify();
1✔
395
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
1✔
396
        }
397
        $this->data = $cache->get($cacheKey);
1✔
398

399
        return $this;
1✔
400
    }
401

402
    /**
403
     * Returns the Data URL (encoded in Base64).
404
     *
405
     * @throws RuntimeException
406
     */
407
    public function dataurl(): string
408
    {
409
        if ($this->data['type'] == 'image' && !Image::isSVG($this)) {
1✔
410
            return Image::getDataUrl($this, (int) $this->config->get('assets.images.quality'));
1✔
411
        }
412

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

416
    /**
417
     * Hashing content of an asset with the specified algo, sha384 by default.
418
     * Used for SRI (Subresource Integrity).
419
     *
420
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
421
     */
422
    public function integrity(string $algo = 'sha384'): string
423
    {
424
        return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
1✔
425
    }
426

427
    /**
428
     * Resizes an image to the given width or/and height.
429
     *
430
     * - If only the width is specified, the height is calculated to preserve the aspect ratio
431
     * - If only the height is specified, the width is calculated to preserve the aspect ratio
432
     * - If both width and height are specified, the image is resized to fit within the given dimensions, image is cropped and centered if necessary
433
     * - If rmAnimation is true, any animation in the image (e.g., GIF) will be removed.
434
     *
435
     * @throws RuntimeException
436
     */
437
    public function resize(?int $width = null, ?int $height = null, bool $rmAnimation = false): self
438
    {
439
        $this->checkImage();
1✔
440

441
        // if no width and no height, return the original image
442
        if ($width === null && $height === null) {
1✔
443
            return $this;
×
444
        }
445

446
        // if equal with and height, return the original image
447
        if ($width == $this->data['width'] && $height == $this->data['height']) {
1✔
448
            return $this;
×
449
        }
450

451
        // if the image width or height is already smaller, return the original image
452
        if ($width !== null && $this->data['width'] <= $width && $height === null) {
1✔
453
            return $this;
1✔
454
        }
455
        if ($height !== null && $this->data['height'] <= $height && $width === null) {
1✔
456
            return $this;
×
457
        }
458

459
        $assetResized = clone $this;
1✔
460
        $assetResized->data['width'] = $width ?? $this->data['width'];
1✔
461
        $assetResized->data['height'] = $height ?? $this->data['height'];
1✔
462

463
        if ($this->isImageInCdn()) {
1✔
464
            if ($width === null) {
×
465
                $assetResized->data['width'] = round($this->data['width'] / ($this->data['height'] / $height));
×
466
            }
467
            if ($height === null) {
×
468
                $assetResized->data['height'] = round($this->data['height'] / ($this->data['width'] / $width));
×
469
            }
470

471
            return $assetResized; // returns asset with the new dimensions only: CDN do the rest of the job
×
472
        }
473

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

476
        $cache = new Cache($this->builder, 'assets');
1✔
477
        $assetResized->cacheTags['quality'] = $quality;
1✔
478
        $assetResized->cacheTags['width'] = $width;
1✔
479
        $assetResized->cacheTags['height'] = $height;
1✔
480
        $cacheKey = $cache->createKey($assetResized, tags: $assetResized->cacheTags);
1✔
481
        if (!$cache->has($cacheKey)) {
1✔
482
            $assetResized->data['content'] = Image::resize($assetResized, $width, $height, $quality, $rmAnimation);
1✔
483
            $assetResized->data['path'] = '/' . Util::joinPath(
1✔
484
                (string) $this->config->get('assets.target'),
1✔
485
                self::IMAGE_THUMB,
1✔
486
                (string) $width . 'x' . (string) $height,
1✔
487
                $assetResized->data['path']
1✔
488
            );
1✔
489
            $assetResized->data['path'] = $this->deduplicateThumbPath($assetResized->data['path']);
1✔
490
            $assetResized->data['width'] = $assetResized->getWidth();
1✔
491
            $assetResized->data['height'] = $assetResized->getHeight();
1✔
492
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
1✔
493

494
            $cache->set($cacheKey, $assetResized->data, $this->config->get('cache.assets.ttl'));
1✔
495
            $this->builder->getLogger()->debug(\sprintf('Asset resized: "%s" (%sx%s)', $assetResized->data['path'], $width, $height));
1✔
496
        }
497
        $assetResized->data = $cache->get($cacheKey);
1✔
498

499
        return $assetResized;
1✔
500
    }
501

502
    /**
503
     * Creates a maskable image (with a padding = 20%).
504
     *
505
     * @throws RuntimeException
506
     */
507
    public function maskable(?int $padding = null): self
508
    {
509
        $this->checkImage();
×
510

511
        if ($padding === null) {
×
512
            $padding = 20; // default padding
×
513
        }
514

515
        $assetMaskable = clone $this;
×
516

517
        $quality = (int) $this->config->get('assets.images.quality');
×
518

519
        $cache = new Cache($this->builder, 'assets');
×
520
        $assetMaskable->cacheTags['maskable'] = true;
×
521
        $cacheKey = $cache->createKey($assetMaskable, tags: $assetMaskable->cacheTags);
×
522
        if (!$cache->has($cacheKey)) {
×
523
            $assetMaskable->data['content'] = Image::maskable($assetMaskable, $quality, $padding);
×
524
            $assetMaskable->data['path'] = '/' . Util::joinPath(
×
525
                (string) $this->config->get('assets.target'),
×
526
                'maskable',
×
527
                $assetMaskable->data['path']
×
528
            );
×
529
            $assetMaskable->data['size'] = \strlen($assetMaskable->data['content']);
×
530

531
            $cache->set($cacheKey, $assetMaskable->data, $this->config->get('cache.assets.ttl'));
×
532
            $this->builder->getLogger()->debug(\sprintf('Asset maskabled: "%s"', $assetMaskable->data['path']));
×
533
        }
534
        $assetMaskable->data = $cache->get($cacheKey);
×
535

536
        return $assetMaskable;
×
537
    }
538

539
    /**
540
     * Converts an image asset to $format format.
541
     *
542
     * @throws RuntimeException
543
     */
544
    public function convert(string $format, ?int $quality = null): self
545
    {
546
        if ($this->data['type'] != 'image') {
1✔
547
            throw new RuntimeException(\sprintf('Unable to convert "%s" (%s) to %s: not an image.', $this->data['path'], $this->data['type'], $format));
×
548
        }
549

550
        if ($quality === null) {
1✔
551
            $quality = (int) $this->config->get('assets.images.quality');
1✔
552
        }
553

554
        $asset = clone $this;
1✔
555
        $asset['ext'] = $format;
1✔
556
        $asset->data['subtype'] = "image/$format";
1✔
557

558
        if ($this->isImageInCdn()) {
1✔
559
            return $asset; // returns the asset with the new extension only: CDN do the rest of the job
×
560
        }
561

562
        $cache = new Cache($this->builder, 'assets');
1✔
563
        $this->cacheTags['quality'] = $quality;
1✔
564
        if ($this->data['width']) {
1✔
565
            $this->cacheTags['width'] = $this->data['width'];
1✔
566
        }
567
        $cacheKey = $cache->createKey($asset, tags: $this->cacheTags);
1✔
568
        if (!$cache->has($cacheKey)) {
1✔
569
            $asset->data['content'] = Image::convert($asset, $format, $quality);
1✔
570
            $asset->data['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']);
1✔
571
            $asset->data['size'] = \strlen($asset->data['content']);
1✔
572
            $cache->set($cacheKey, $asset->data, $this->config->get('cache.assets.ttl'));
1✔
573
            $this->builder->getLogger()->debug(\sprintf('Asset converted: "%s" (%s -> %s)', $asset->data['path'], $this->data['ext'], $format));
1✔
574
        }
575
        $asset->data = $cache->get($cacheKey);
1✔
576

577
        return $asset;
1✔
578
    }
579

580
    /**
581
     * Converts an image asset to WebP format.
582
     *
583
     * @throws RuntimeException
584
     */
585
    public function webp(?int $quality = null): self
586
    {
587
        return $this->convert('webp', $quality);
×
588
    }
589

590
    /**
591
     * Converts an image asset to AVIF format.
592
     *
593
     * @throws RuntimeException
594
     */
595
    public function avif(?int $quality = null): self
596
    {
597
        return $this->convert('avif', $quality);
×
598
    }
599

600
    /**
601
     * Is the asset an image and is it in CDN?
602
     */
603
    public function isImageInCdn(): bool
604
    {
605
        if (
606
            $this->data['type'] == 'image'
1✔
607
            && $this->config->isEnabled('assets.images.cdn')
1✔
608
            && $this->data['ext'] != 'ico'
1✔
609
            && (Image::isSVG($this) && $this->config->isEnabled('assets.images.cdn.svg'))
1✔
610
        ) {
611
            return true;
×
612
        }
613
        // handle remote image?
614
        if ($this->data['url'] !== null && $this->config->isEnabled('assets.images.cdn.remote')) {
1✔
615
            return true;
×
616
        }
617

618
        return false;
1✔
619
    }
620

621
    /**
622
     * Returns the width of an image/SVG or a video.
623
     *
624
     * @throws RuntimeException
625
     */
626
    public function getWidth(): ?int
627
    {
628
        switch ($this->data['type']) {
1✔
629
            case 'image':
1✔
630
                if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
1✔
631
                    return (int) $svg->width;
1✔
632
                }
633
                if (false === $size = $this->getImageSize()) {
1✔
634
                    throw new RuntimeException(\sprintf('Unable to get width of "%s".', $this->data['path']));
×
635
                }
636

637
                return $size[0];
1✔
638
            case 'video':
1✔
639
                return $this->getVideo()['width'];
1✔
640
        }
641

642
        return null;
1✔
643
    }
644

645
    /**
646
     * Returns the height of an image/SVG or a video.
647
     *
648
     * @throws RuntimeException
649
     */
650
    public function getHeight(): ?int
651
    {
652
        switch ($this->data['type']) {
1✔
653
            case 'image':
1✔
654
                if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
1✔
655
                    return (int) $svg->height;
1✔
656
                }
657
                if (false === $size = $this->getImageSize()) {
1✔
658
                    throw new RuntimeException(\sprintf('Unable to get height of "%s".', $this->data['path']));
×
659
                }
660

661
                return $size[1];
1✔
662
            case 'video':
1✔
663
                return $this->getVideo()['height'];
1✔
664
        }
665

666
        return null;
1✔
667
    }
668

669
    /**
670
     * Returns audio file infos:
671
     * - duration (in seconds.microseconds)
672
     * - bitrate (in bps)
673
     * - channel ('stereo', 'dual_mono', 'joint_stereo' or 'mono')
674
     *
675
     * @see https://github.com/wapmorgan/Mp3Info
676
     */
677
    public function getAudio(): array
678
    {
679
        $audio = new Mp3Info($this->data['file']);
1✔
680

681
        return [
1✔
682
            'duration' => $audio->duration,
1✔
683
            'bitrate'  => $audio->bitRate,
1✔
684
            'channel'  => $audio->channel,
1✔
685
        ];
1✔
686
    }
687

688
    /**
689
     * Returns video file infos:
690
     * - duration (in seconds)
691
     * - width (in pixels)
692
     * - height (in pixels)
693
     *
694
     * @see https://github.com/JamesHeinrich/getID3
695
     */
696
    public function getVideo(): array
697
    {
698
        if ($this->data['type'] !== 'video') {
1✔
699
            throw new RuntimeException(\sprintf('Unable to get video infos of "%s".', $this->data['path']));
×
700
        }
701

702
        $video = (new \getID3())->analyze($this->data['file']);
1✔
703

704
        return [
1✔
705
            'duration' => $video['playtime_seconds'],
1✔
706
            'width'    => $video['video']['resolution_x'],
1✔
707
            'height'   => $video['video']['resolution_y'],
1✔
708
        ];
1✔
709
    }
710

711
    /**
712
     * Builds a relative path from a URL.
713
     * Used for remote files.
714
     */
715
    public static function buildPathFromUrl(string $url): string
716
    {
717
        $host = parse_url($url, PHP_URL_HOST);
1✔
718
        $path = \is_string($path = parse_url($url, PHP_URL_PATH)) && $path !== '/' ? $path : '-index.html'; // if URL is only a domain, set path to '-index.html' to avoid empty path
1✔
719
        $query = parse_url($url, PHP_URL_QUERY);
1✔
720
        $ext = pathinfo($path, \PATHINFO_EXTENSION);
1✔
721
        // Google Fonts hack
722
        if (Util\Str::endsWith($path, '/css') || Util\Str::endsWith($path, '/css2')) {
1✔
723
            $ext = 'css';
1✔
724
        }
725

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

729
    /**
730
     * Replaces some characters by '_'.
731
     */
732
    public static function sanitize(string $string): string
733
    {
734
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
1✔
735
    }
736

737
    /**
738
     * Add hash to the file name.
739
     */
740
    protected function doFingerprint(): self
741
    {
742
        $hash = hash('xxh128', $this->data['content']);
1✔
743
        $this->data['path'] = preg_replace(
1✔
744
            '/\.' . $this->data['ext'] . '$/m',
1✔
745
            ".$hash." . $this->data['ext'],
1✔
746
            $this->data['path']
1✔
747
        );
1✔
748
        $this->builder->getLogger()->debug(\sprintf('Asset fingerprinted: "%s"', $this->data['path']));
1✔
749

750
        return $this;
1✔
751
    }
752

753
    /**
754
     * Compiles a SCSS.
755
     *
756
     * @throws RuntimeException
757
     */
758
    protected function doCompile(): self
759
    {
760
        // abort if not a SCSS file
761
        if ($this->data['ext'] != 'scss') {
1✔
762
            return $this;
1✔
763
        }
764
        $scssPhp = new Compiler();
1✔
765
        // import paths
766
        $importDir = [];
1✔
767
        $importDir[] = Util::joinPath($this->config->getStaticPath());
1✔
768
        $importDir[] = Util::joinPath($this->config->getAssetsPath());
1✔
769
        $scssDir = (array) $this->config->get('assets.compile.import');
1✔
770
        $themes = $this->config->getTheme() ?? [];
1✔
771
        foreach ($scssDir as $dir) {
1✔
772
            $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir);
1✔
773
            $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir);
1✔
774
            $importDir[] = Util::joinPath(\dirname($this->data['file']), $dir);
1✔
775
            foreach ($themes as $theme) {
1✔
776
                $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir"));
1✔
777
                $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir"));
1✔
778
            }
779
        }
780
        $scssPhp->setQuietDeps(true);
1✔
781
        $scssPhp->setImportPaths(array_unique($importDir));
1✔
782
        // adds source map
783
        if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
1✔
784
            $importDir = [];
×
785
            $assetDir = (string) $this->config->get('assets.dir');
×
786
            $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR . $assetDir . DIRECTORY_SEPARATOR);
×
787
            $fileRelPath = substr($this->data['file'], $assetDirPos + 8);
×
788
            $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath);
×
789
            $importDir[] = \dirname($filePath);
×
790
            foreach ($scssDir as $dir) {
×
791
                $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir);
×
792
            }
793
            $scssPhp->setImportPaths(array_unique($importDir));
×
794
            $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE);
×
795
            $scssPhp->setSourceMapOptions([
×
796
                'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()),
×
797
                'sourceRoot'        => '/',
×
798
            ]);
×
799
        }
800
        // defines output style
801
        $outputStyles = ['expanded', 'compressed'];
1✔
802
        $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
1✔
803
        if (!\in_array($outputStyle, $outputStyles)) {
1✔
804
            throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles)));
×
805
        }
806
        $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED);
1✔
807
        // set variables
808
        $variables = $this->config->get('assets.compile.variables');
1✔
809
        if (!empty($variables)) {
1✔
810
            $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
1✔
811
            $scssPhp->replaceVariables($variables);
1✔
812
        }
813
        // debug
814
        if ($this->builder->isDebug()) {
1✔
815
            $scssPhp->setQuietDeps(false);
1✔
816
            $this->builder->getLogger()->debug(\sprintf("SCSS compiler imported paths:\n%s", Util\Str::arrayToList(array_unique($importDir))));
1✔
817
        }
818
        // update data
819
        $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']);
1✔
820
        $this->data['ext'] = 'css';
1✔
821
        $this->data['type'] = 'text';
1✔
822
        $this->data['subtype'] = 'text/css';
1✔
823
        $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss();
1✔
824
        $this->data['size'] = \strlen($this->data['content']);
1✔
825

826
        $this->builder->getLogger()->debug(\sprintf('Asset compiled: "%s"', $this->data['path']));
1✔
827

828
        return $this;
1✔
829
    }
830

831
    /**
832
     * Minifying a CSS or a JS + cache.
833
     *
834
     * @throws RuntimeException
835
     */
836
    protected function doMinify(): self
837
    {
838
        // compile SCSS files
839
        if ($this->data['ext'] == 'scss') {
1✔
840
            $this->doCompile();
×
841
        }
842
        // abort if already minified
843
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
1✔
844
            return $this;
×
845
        }
846
        // abord if not a CSS or JS file
847
        if (!\in_array($this->data['ext'], ['css', 'js'])) {
1✔
848
            return $this;
×
849
        }
850
        // in debug mode: disable minify to preserve inline source map
851
        if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
1✔
852
            return $this;
×
853
        }
854
        switch ($this->data['ext']) {
1✔
855
            case 'css':
1✔
856
                $minifier = new Minify\CSS($this->data['content']);
1✔
857
                break;
1✔
858
            case 'js':
1✔
859
                $minifier = new Minify\JS($this->data['content']);
1✔
860
                break;
1✔
861
            default:
862
                throw new RuntimeException(\sprintf('Unable to minify "%s".', $this->data['path']));
×
863
        }
864
        $this->data['content'] = $minifier->minify();
1✔
865
        $this->data['size'] = \strlen($this->data['content']);
1✔
866

867
        $this->builder->getLogger()->debug(\sprintf('Asset minified: "%s"', $this->data['path']));
1✔
868

869
        return $this;
1✔
870
    }
871

872
    /**
873
     * Returns local file path and updated path, or throw an exception.
874
     * If $fallback path is set, it will be used if the remote file is not found.
875
     *
876
     * Try to locate the file in:
877
     *   (1. remote file)
878
     *   1. assets
879
     *   2. themes/<theme>/assets
880
     *   3. static
881
     *   4. themes/<theme>/static
882
     *
883
     * @throws RuntimeException
884
     */
885
    private function locateFile(string $path, ?string $fallback = null, ?string $userAgent = null, ?string $language = null): array
886
    {
887
        // remote file
888
        if (Util\File::isRemote($path)) {
1✔
889
            try {
890
                $url = $path;
1✔
891
                $path = Util::joinPath(
1✔
892
                    (string) $this->config->get('assets.target'),
1✔
893
                    self::buildPathFromUrl($url)
1✔
894
                );
1✔
895
                $cache = new Cache($this->builder, 'assets/_remote');
1✔
896
                if (!$cache->has($path)) {
1✔
897
                    $content = $this->getRemoteFileContent($url, $userAgent);
1✔
898
                    $cache->set($path, [
1✔
899
                        'content' => $content,
1✔
900
                        'path'    => $path,
1✔
901
                    ], $this->config->get('cache.assets.remote.ttl'));
1✔
902
                }
903
                return [
1✔
904
                    'file' => $cache->getContentFile($path),
1✔
905
                    'path' => $path,
1✔
906
                ];
1✔
907
            } catch (RuntimeException $e) {
1✔
908
                if (empty($fallback)) {
1✔
909
                    throw new RuntimeException($e->getMessage());
×
910
                }
911
                $path = $fallback;
1✔
912
            }
913
        }
914

915
        $localizedPath = self::buildLocalizedPath($path, $language);
1✔
916

917
        // checks in assets/
918
        if ($localizedPath !== null) {
1✔
919
            $file = Util::joinFile($this->config->getAssetsPath(), $localizedPath);
1✔
920
            if (Util\File::getFS()->exists($file)) {
1✔
921
                return [
1✔
922
                    'file' => $file,
1✔
923
                    'path' => $localizedPath,
1✔
924
                ];
1✔
925
            }
926
        }
927
        $file = Util::joinFile($this->config->getAssetsPath(), $path);
1✔
928
        if (Util\File::getFS()->exists($file)) {
1✔
929
            return [
1✔
930
                'file' => $file,
1✔
931
                'path' => $path,
1✔
932
            ];
1✔
933
        }
934

935
        // checks in each themes/<theme>/assets/
936
        foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
937
            if ($localizedPath !== null) {
1✔
NEW
938
                $file = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $localizedPath);
×
NEW
939
                if (Util\File::getFS()->exists($file)) {
×
NEW
940
                    return [
×
NEW
941
                        'file' => $file,
×
NEW
942
                        'path' => $localizedPath,
×
NEW
943
                    ];
×
944
                }
945
            }
946
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
1✔
947
            if (Util\File::getFS()->exists($file)) {
1✔
948
                return [
1✔
949
                    'file' => $file,
1✔
950
                    'path' => $path,
1✔
951
                ];
1✔
952
            }
953
        }
954

955
        // checks in static/
956
        if ($localizedPath !== null) {
1✔
NEW
957
            $file = Util::joinFile($this->config->getStaticPath(), $localizedPath);
×
NEW
958
            if (Util\File::getFS()->exists($file)) {
×
NEW
959
                return [
×
NEW
960
                    'file' => $file,
×
NEW
961
                    'path' => $localizedPath,
×
NEW
962
                ];
×
963
            }
964
        }
965
        $file = Util::joinFile($this->config->getStaticPath(), $path);
1✔
966
        if (Util\File::getFS()->exists($file)) {
1✔
967
            return [
1✔
968
                'file' => $file,
1✔
969
                'path' => $path,
1✔
970
            ];
1✔
971
        }
972

973
        // checks in each themes/<theme>/static/
974
        foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
975
            if ($localizedPath !== null) {
1✔
NEW
976
                $file = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $localizedPath);
×
NEW
977
                if (Util\File::getFS()->exists($file)) {
×
NEW
978
                    return [
×
NEW
979
                        'file' => $file,
×
NEW
980
                        'path' => $localizedPath,
×
NEW
981
                    ];
×
982
                }
983
            }
984
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
1✔
985
            if (Util\File::getFS()->exists($file)) {
1✔
986
                return [
1✔
987
                    'file' => $file,
1✔
988
                    'path' => $path,
1✔
989
                ];
1✔
990
            }
991
        }
992

993
        throw new RuntimeException(\sprintf('Unable to locate file "%s".', $path));
1✔
994
    }
995

996
    private static function buildLocalizedPath(string $path, ?string $language = null): ?string
997
    {
998
        if ($language === null || $language === '') {
1✔
999
            return null;
1✔
1000
        }
1001

1002
        $pathInfo = pathinfo($path);
1✔
1003
        if (empty($pathInfo['extension']) || empty($pathInfo['filename'])) {
1✔
NEW
1004
            return null;
×
1005
        }
1006

1007
        $filenameParts = explode('.', $pathInfo['filename']);
1✔
1008
        if (end($filenameParts) === $language) {
1✔
NEW
1009
            return null;
×
1010
        }
1011

1012
        $localizedFilename = \sprintf('%s.%s.%s', $pathInfo['filename'], $language, $pathInfo['extension']);
1✔
1013
        if (empty($pathInfo['dirname']) || $pathInfo['dirname'] === '.') {
1✔
NEW
1014
            return $localizedFilename;
×
1015
        }
1016

1017
        return Util::joinPath($pathInfo['dirname'], $localizedFilename);
1✔
1018
    }
1019

1020
    /**
1021
     * Try to get remote file content.
1022
     * Returns file content or throw an exception.
1023
     *
1024
     * @throws RuntimeException
1025
     */
1026
    private function getRemoteFileContent(string $path, ?string $userAgent = null): string
1027
    {
1028
        if (!Util\File::isRemoteExists($path)) {
1✔
1029
            throw new RuntimeException(\sprintf('Unable to get remote file "%s".', $path));
1✔
1030
        }
1031
        if (false === $content = Util\File::fileGetContents($path, $userAgent)) {
1✔
1032
            throw new RuntimeException(\sprintf('Unable to get content of remote file "%s".', $path));
×
1033
        }
1034
        if (\strlen($content) <= 1) {
1✔
1035
            throw new RuntimeException(\sprintf('Remote file "%s" is empty.', $path));
×
1036
        }
1037

1038
        return $content;
1✔
1039
    }
1040

1041
    /**
1042
     * Optimizing $filepath image.
1043
     * Returns the new file size.
1044
     */
1045
    private function optimizeImage(string $filepath, string $path, int $quality): int
1046
    {
1047
        $message = \sprintf('Asset not optimized: "%s"', $path);
1✔
1048
        $sizeBefore = filesize($filepath);
1✔
1049
        Optimizer::create($quality)->optimize($filepath);
1✔
1050
        $sizeAfter = filesize($filepath);
1✔
1051
        if ($sizeAfter < $sizeBefore) {
1✔
1052
            $message = \sprintf('Asset optimized: "%s" (%s Ko -> %s Ko)', $path, ceil($sizeBefore / 1000), ceil($sizeAfter / 1000));
×
1053
        }
1054
        $this->builder->getLogger()->debug($message);
1✔
1055

1056
        return $sizeAfter;
1✔
1057
    }
1058

1059
    /**
1060
     * Returns image size informations.
1061
     *
1062
     * @see https://www.php.net/manual/function.getimagesize.php
1063
     *
1064
     * @throws RuntimeException
1065
     */
1066
    private function getImageSize(): array|false
1067
    {
1068
        if (!$this->data['type'] == 'image') {
1✔
1069
            return false;
×
1070
        }
1071

1072
        try {
1073
            if (false === $size = getimagesizefromstring($this->data['content'])) {
1✔
1074
                return false;
1✔
1075
            }
1076
        } catch (\Exception $e) {
×
1077
            throw new RuntimeException(\sprintf('Handling asset "%s" failed: "%s".', $this->data['path'], $e->getMessage()));
×
1078
        }
1079

1080
        return $size;
1✔
1081
    }
1082

1083
    /**
1084
     * Builds CDN image URL.
1085
     */
1086
    private function buildImageCdnUrl(): string
1087
    {
1088
        return str_replace(
×
1089
            [
×
1090
                '%account%',
×
1091
                '%image_url%',
×
1092
                '%width%',
×
1093
                '%quality%',
×
1094
                '%format%',
×
1095
            ],
×
1096
            [
×
1097
                $this->config->get('assets.images.cdn.account') ?? '',
×
1098
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical') ?? true]), '/'),
×
1099
                $this->data['width'],
×
1100
                (int) $this->config->get('assets.images.quality'),
×
1101
                $this->data['ext'],
×
1102
            ],
×
1103
            (string) $this->config->get('assets.images.cdn.url')
×
1104
        );
×
1105
    }
1106

1107
    /**
1108
     * Checks if the asset is not missing and is typed as an image.
1109
     *
1110
     * @throws RuntimeException
1111
     */
1112
    private function checkImage(): void
1113
    {
1114
        if ($this->isMissing()) {
1✔
1115
            throw new RuntimeException(\sprintf('Unable to resize "%s": file not found.', $this->data['path']));
×
1116
        }
1117
        if ($this->data['type'] != 'image') {
1✔
1118
            throw new RuntimeException(\sprintf('Unable to resize "%s": not an image.', $this->data['path']));
×
1119
        }
1120
    }
1121

1122
    /**
1123
     * Remove redondant '/thumbnails/<width(xheight)>/' in the path.
1124
     */
1125
    private function deduplicateThumbPath(string $path): string
1126
    {
1127
        // https://regex101.com/r/0r7FMY/1
1128
        $pattern = '/(' . self::IMAGE_THUMB . '\/(\d+){0,1}x(\d+){0,1}\/)(' . self::IMAGE_THUMB . '\/(\d+){0,1}x(\d+){0,1}\/)(.*)/i';
1✔
1129

1130
        if (null === $result = preg_replace($pattern, '$1$7', $path)) {
1✔
1131
            return $path;
×
1132
        }
1133

1134
        return $result;
1✔
1135
    }
1136
}
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