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

Cecilapp / Cecil / 22045060359

15 Feb 2026 11:24PM UTC coverage: 82.509% (+0.1%) from 82.382%
22045060359

push

github

ArnaudLigny
Handle domain-only paths; fetch HTML via Asset

Set a default path ('-index.html') when buildPathFromUrl encounters a URL with no path so extension detection and path handling work for domain-only URLs. Use that path when computing the extension. Replace direct file_get_contents() usage in htmlImageFromWebsite with creating an Asset (ignore_missing) to fetch the page, log a warning and return null when the HTML asset is missing, and then extract the image from the asset content. Also uncomment the HTML image-from-URL example in the test fixture.

5 of 7 new or added lines in 2 files covered. (71.43%)

55 existing lines in 2 files now uncovered.

3321 of 4025 relevant lines covered (82.51%)

0.83 hits per line

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

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

112
        // handles options
113
        $options = array_merge(
1✔
114
            [
1✔
115
                'filename'       => '',
1✔
116
                'ignore_missing' => false,
1✔
117
                'fingerprint'    => $this->config->isEnabled('assets.fingerprint'),
1✔
118
                'minify'         => $this->config->isEnabled('assets.minify'),
1✔
119
                'optimize'       => $this->config->isEnabled('assets.images.optimize'),
1✔
120
                'fallback'       => '',
1✔
121
                'useragent'      => (string) $this->config->get('assets.remote.useragent.default'),
1✔
122
            ],
1✔
123
            \is_array($options) ? $options : []
1✔
124
        );
1✔
125

126
        // cache for "locate file(s)"
127
        $cache = new Cache($this->builder, 'assets');
1✔
128
        $locateCacheKey = \sprintf('%s_locate__%s__%s', $options['filename'] ?: implode('_', $paths), Builder::getBuildId(), Builder::getVersion());
1✔
129

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

189
        // missing
190
        if ($this->isMissing()) {
1✔
191
            return;
1✔
192
        }
193

194
        // cache for "process asset"
195
        $cache = new Cache($this->builder, 'assets');
1✔
196
        // create cache tags from options
197
        $this->cacheTags = $options;
1✔
198
        // remove unnecessary cache tags
199
        unset($this->cacheTags['optimize'], $this->cacheTags['ignore_missing'], $this->cacheTags['fallback'], $this->cacheTags['useragent']);
1✔
200
        if (!\in_array($this->data['ext'], ['css', 'js', 'scss'])) {
1✔
201
            unset($this->cacheTags['minify']);
1✔
202
        }
203
        // optimize image?
204
        $optimize = false;
1✔
205
        if ($options['optimize'] && $this->data['type'] == 'image' && !$this->isImageInCdn()) {
1✔
206
            $optimize = true;
1✔
207
            $quality = (int) $this->config->get('assets.images.quality');
1✔
208
            $this->cacheTags['quality'] = $quality;
1✔
209
        }
210
        $cacheKey = $cache->createKey($this, tags: $this->cacheTags);
1✔
211
        if (!$cache->has($cacheKey)) {
1✔
212
            // fingerprinting
213
            if ($options['fingerprint']) {
1✔
214
                $this->doFingerprint();
×
215
            }
216
            // compiling Sass files
217
            $this->doCompile();
1✔
218
            // minifying (CSS and JavaScript files)
219
            if ($options['minify']) {
1✔
220
                $this->doMinify();
×
221
            }
222
            // get width and height
223
            $this->data['width'] = $this->getWidth();
1✔
224
            $this->data['height'] = $this->getHeight();
1✔
225
            // get image exif
226
            if ($this->data['subtype'] == 'image/jpeg') {
1✔
227
                $this->data['exif'] = Util\File::readExif($this->data['file']);
1✔
228
            }
229
            // get duration
230
            if ($this->data['type'] == 'audio') {
1✔
231
                $this->data['duration'] = $this->getAudio()['duration'];
1✔
232
            }
233
            if ($this->data['type'] == 'video') {
1✔
234
                $this->data['duration'] = $this->getVideo()['duration'];
1✔
235
            }
236
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
1✔
237
            $this->builder->getLogger()->debug(\sprintf('Asset cached: "%s"', $this->data['path']));
1✔
238
            // optimizing images files (in cache directory)
239
            if ($optimize) {
1✔
240
                $this->optimizeImage($cache->getContentFile($this->data['path']), $this->data['path'], $quality);
1✔
241
            }
242
        }
243
        $this->data = $cache->get($cacheKey);
1✔
244
    }
245

246
    /**
247
     * Returns path.
248
     */
249
    public function __toString(): string
250
    {
251
        $this->save();
1✔
252

253
        if ($this->isImageInCdn()) {
1✔
254
            return $this->buildImageCdnUrl();
×
255
        }
256

257
        if ($this->builder->getConfig()->isEnabled('canonicalurl')) {
1✔
258
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
×
259
        }
260

261
        return $this->data['path'];
1✔
262
    }
263

264
    /**
265
     * Implements \ArrayAccess.
266
     */
267
    #[\ReturnTypeWillChange]
268
    public function offsetSet($offset, $value): void
269
    {
270
        if (!\is_null($offset)) {
1✔
271
            $this->data[$offset] = $value;
1✔
272
        }
273
    }
274

275
    /**
276
     * Implements \ArrayAccess.
277
     */
278
    #[\ReturnTypeWillChange]
279
    public function offsetExists($offset): bool
280
    {
281
        return isset($this->data[$offset]);
1✔
282
    }
283

284
    /**
285
     * Implements \ArrayAccess.
286
     */
287
    #[\ReturnTypeWillChange]
288
    public function offsetUnset($offset): void
289
    {
290
        unset($this->data[$offset]);
×
291
    }
292

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

302
    /**
303
     * Saves the asset by adding its path to the build assets list.
304
     * Skips assets marked as missing and validates that the asset file exists in cache before adding it.
305
     *
306
     * @throws RuntimeException
307
     */
308
    public function save(): void
309
    {
310
        if ($this->isMissing()) {
1✔
311
            return;
1✔
312
        }
313

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

319
        $this->builder->addToAssetsList($this->data['path']);
1✔
320
    }
321

322
    /**
323
     * Checks if the asset is missing.
324
     */
325
    public function isMissing(): bool
326
    {
327
        return $this->data['missing'];
1✔
328
    }
329

330
    /**
331
     * Add hash to the file name + cache.
332
     */
333
    public function fingerprint(): self
334
    {
335
        $this->cacheTags['fingerprint'] = true;
1✔
336
        $cache = new Cache($this->builder, 'assets');
1✔
337
        $cacheKey = $cache->createKey($this, tags: $this->cacheTags);
1✔
338
        if (!$cache->has($cacheKey)) {
1✔
339
            $this->doFingerprint();
1✔
340
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
1✔
341
        }
342
        $this->data = $cache->get($cacheKey);
1✔
343

344
        return $this;
1✔
345
    }
346

347
    /**
348
     * Compiles a SCSS + cache.
349
     *
350
     * @throws RuntimeException
351
     */
352
    public function compile(): self
353
    {
354
        $this->cacheTags['compile'] = 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->doCompile();
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
     * Minifying a CSS or a JS.
368
     */
369
    public function minify(): self
370
    {
371
        $this->cacheTags['minify'] = true;
1✔
372
        $cache = new Cache($this->builder, 'assets');
1✔
373
        $cacheKey = $cache->createKey($this, tags: $this->cacheTags);
1✔
374
        if (!$cache->has($cacheKey)) {
1✔
375
            $this->doMinify();
1✔
376
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
1✔
377
        }
378
        $this->data = $cache->get($cacheKey);
1✔
379

380
        return $this;
1✔
381
    }
382

383
    /**
384
     * Returns the Data URL (encoded in Base64).
385
     *
386
     * @throws RuntimeException
387
     */
388
    public function dataurl(): string
389
    {
390
        if ($this->data['type'] == 'image' && !Image::isSVG($this)) {
1✔
391
            return Image::getDataUrl($this, (int) $this->config->get('assets.images.quality'));
1✔
392
        }
393

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

397
    /**
398
     * Hashing content of an asset with the specified algo, sha384 by default.
399
     * Used for SRI (Subresource Integrity).
400
     *
401
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
402
     */
403
    public function integrity(string $algo = 'sha384'): string
404
    {
405
        return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
1✔
406
    }
407

408
    /**
409
     * Resizes an image to the given width or/and height.
410
     *
411
     * - If only the width is specified, the height is calculated to preserve the aspect ratio
412
     * - If only the height is specified, the width is calculated to preserve the aspect ratio
413
     * - If both width and height are specified, the image is resized to fit within the given dimensions, image is cropped and centered if necessary
414
     * - If rmAnimation is true, any animation in the image (e.g., GIF) will be removed.
415
     *
416
     * @throws RuntimeException
417
     */
418
    public function resize(?int $width = null, ?int $height = null, bool $rmAnimation = false): self
419
    {
420
        $this->checkImage();
1✔
421

422
        // if no width and no height, return the original image
423
        if ($width === null && $height === null) {
1✔
UNCOV
424
            return $this;
×
425
        }
426

427
        // if equal with and height, return the original image
428
        if ($width == $this->data['width'] && $height == $this->data['height']) {
1✔
429
            return $this;
×
430
        }
431

432
        // if the image width or height is already smaller, return the original image
433
        if ($width !== null && $this->data['width'] <= $width && $height === null) {
1✔
434
            return $this;
1✔
435
        }
436
        if ($height !== null && $this->data['height'] <= $height && $width === null) {
1✔
437
            return $this;
×
438
        }
439

440
        $assetResized = clone $this;
1✔
441
        $assetResized->data['width'] = $width ?? $this->data['width'];
1✔
442
        $assetResized->data['height'] = $height ?? $this->data['height'];
1✔
443

444
        if ($this->isImageInCdn()) {
1✔
UNCOV
445
            if ($width === null) {
×
UNCOV
446
                $assetResized->data['width'] = round($this->data['width'] / ($this->data['height'] / $height));
×
447
            }
UNCOV
448
            if ($height === null) {
×
UNCOV
449
                $assetResized->data['height'] = round($this->data['height'] / ($this->data['width'] / $width));
×
450
            }
451

UNCOV
452
            return $assetResized; // returns asset with the new dimensions only: CDN do the rest of the job
×
453
        }
454

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

457
        $cache = new Cache($this->builder, 'assets');
1✔
458
        $assetResized->cacheTags['quality'] = $quality;
1✔
459
        $assetResized->cacheTags['width'] = $width;
1✔
460
        $assetResized->cacheTags['height'] = $height;
1✔
461
        $cacheKey = $cache->createKey($assetResized, tags: $assetResized->cacheTags);
1✔
462
        if (!$cache->has($cacheKey)) {
1✔
463
            $assetResized->data['content'] = Image::resize($assetResized, $width, $height, $quality, $rmAnimation);
1✔
464
            $assetResized->data['path'] = '/' . Util::joinPath(
1✔
465
                (string) $this->config->get('assets.target'),
1✔
466
                self::IMAGE_THUMB,
1✔
467
                (string) $width . 'x' . (string) $height,
1✔
468
                $assetResized->data['path']
1✔
469
            );
1✔
470
            $assetResized->data['path'] = $this->deduplicateThumbPath($assetResized->data['path']);
1✔
471
            $assetResized->data['width'] = $assetResized->getWidth();
1✔
472
            $assetResized->data['height'] = $assetResized->getHeight();
1✔
473
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
1✔
474

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

480
        return $assetResized;
1✔
481
    }
482

483
    /**
484
     * Creates a maskable image (with a padding = 20%).
485
     *
486
     * @throws RuntimeException
487
     */
488
    public function maskable(?int $padding = null): self
489
    {
490
        $this->checkImage();
×
491

492
        if ($padding === null) {
×
493
            $padding = 20; // default padding
×
494
        }
495

496
        $assetMaskable = clone $this;
×
497

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

500
        $cache = new Cache($this->builder, 'assets');
×
501
        $assetMaskable->cacheTags['maskable'] = true;
×
502
        $cacheKey = $cache->createKey($assetMaskable, tags: $assetMaskable->cacheTags);
×
UNCOV
503
        if (!$cache->has($cacheKey)) {
×
504
            $assetMaskable->data['content'] = Image::maskable($assetMaskable, $quality, $padding);
×
505
            $assetMaskable->data['path'] = '/' . Util::joinPath(
×
UNCOV
506
                (string) $this->config->get('assets.target'),
×
507
                'maskable',
×
UNCOV
508
                $assetMaskable->data['path']
×
509
            );
×
UNCOV
510
            $assetMaskable->data['size'] = \strlen($assetMaskable->data['content']);
×
511

UNCOV
512
            $cache->set($cacheKey, $assetMaskable->data, $this->config->get('cache.assets.ttl'));
×
UNCOV
513
            $this->builder->getLogger()->debug(\sprintf('Asset maskabled: "%s"', $assetMaskable->data['path']));
×
514
        }
UNCOV
515
        $assetMaskable->data = $cache->get($cacheKey);
×
516

UNCOV
517
        return $assetMaskable;
×
518
    }
519

520
    /**
521
     * Converts an image asset to $format format.
522
     *
523
     * @throws RuntimeException
524
     */
525
    public function convert(string $format, ?int $quality = null): self
526
    {
527
        if ($this->data['type'] != 'image') {
1✔
UNCOV
528
            throw new RuntimeException(\sprintf('Unable to convert "%s" (%s) to %s: not an image.', $this->data['path'], $this->data['type'], $format));
×
529
        }
530

531
        if ($quality === null) {
1✔
532
            $quality = (int) $this->config->get('assets.images.quality');
1✔
533
        }
534

535
        $asset = clone $this;
1✔
536
        $asset['ext'] = $format;
1✔
537
        $asset->data['subtype'] = "image/$format";
1✔
538

539
        if ($this->isImageInCdn()) {
1✔
UNCOV
540
            return $asset; // returns the asset with the new extension only: CDN do the rest of the job
×
541
        }
542

543
        $cache = new Cache($this->builder, 'assets');
1✔
544
        $this->cacheTags['quality'] = $quality;
1✔
545
        if ($this->data['width']) {
1✔
546
            $this->cacheTags['width'] = $this->data['width'];
1✔
547
        }
548
        $cacheKey = $cache->createKey($asset, tags: $this->cacheTags);
1✔
549
        if (!$cache->has($cacheKey)) {
1✔
550
            $asset->data['content'] = Image::convert($asset, $format, $quality);
1✔
551
            $asset->data['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']);
1✔
552
            $asset->data['size'] = \strlen($asset->data['content']);
1✔
553
            $cache->set($cacheKey, $asset->data, $this->config->get('cache.assets.ttl'));
1✔
554
            $this->builder->getLogger()->debug(\sprintf('Asset converted: "%s" (%s -> %s)', $asset->data['path'], $this->data['ext'], $format));
1✔
555
        }
556
        $asset->data = $cache->get($cacheKey);
1✔
557

558
        return $asset;
1✔
559
    }
560

561
    /**
562
     * Converts an image asset to WebP format.
563
     *
564
     * @throws RuntimeException
565
     */
566
    public function webp(?int $quality = null): self
567
    {
UNCOV
568
        return $this->convert('webp', $quality);
×
569
    }
570

571
    /**
572
     * Converts an image asset to AVIF format.
573
     *
574
     * @throws RuntimeException
575
     */
576
    public function avif(?int $quality = null): self
577
    {
UNCOV
578
        return $this->convert('avif', $quality);
×
579
    }
580

581
    /**
582
     * Is the asset an image and is it in CDN?
583
     */
584
    public function isImageInCdn(): bool
585
    {
586
        if (
587
            $this->data['type'] == 'image'
1✔
588
            && $this->config->isEnabled('assets.images.cdn')
1✔
589
            && $this->data['ext'] != 'ico'
1✔
590
            && (Image::isSVG($this) && $this->config->isEnabled('assets.images.cdn.svg'))
1✔
591
        ) {
UNCOV
592
            return true;
×
593
        }
594
        // handle remote image?
595
        if ($this->data['url'] !== null && $this->config->isEnabled('assets.images.cdn.remote')) {
1✔
UNCOV
596
            return true;
×
597
        }
598

599
        return false;
1✔
600
    }
601

602
    /**
603
     * Returns the width of an image/SVG or a video.
604
     *
605
     * @throws RuntimeException
606
     */
607
    public function getWidth(): ?int
608
    {
609
        switch ($this->data['type']) {
1✔
610
            case 'image':
1✔
611
                if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) {
1✔
612
                    return (int) $svg->width;
1✔
613
                }
614
                if (false === $size = $this->getImageSize()) {
1✔
UNCOV
615
                    throw new RuntimeException(\sprintf('Unable to get width of "%s".', $this->data['path']));
×
616
                }
617

618
                return $size[0];
1✔
619
            case 'video':
1✔
620
                return $this->getVideo()['width'];
1✔
621
        }
622

623
        return null;
1✔
624
    }
625

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

642
                return $size[1];
1✔
643
            case 'video':
1✔
644
                return $this->getVideo()['height'];
1✔
645
        }
646

647
        return null;
1✔
648
    }
649

650
    /**
651
     * Returns audio file infos:
652
     * - duration (in seconds.microseconds)
653
     * - bitrate (in bps)
654
     * - channel ('stereo', 'dual_mono', 'joint_stereo' or 'mono')
655
     *
656
     * @see https://github.com/wapmorgan/Mp3Info
657
     */
658
    public function getAudio(): array
659
    {
660
        $audio = new Mp3Info($this->data['file']);
1✔
661

662
        return [
1✔
663
            'duration' => $audio->duration,
1✔
664
            'bitrate'  => $audio->bitRate,
1✔
665
            'channel'  => $audio->channel,
1✔
666
        ];
1✔
667
    }
668

669
    /**
670
     * Returns video file infos:
671
     * - duration (in seconds)
672
     * - width (in pixels)
673
     * - height (in pixels)
674
     *
675
     * @see https://github.com/JamesHeinrich/getID3
676
     */
677
    public function getVideo(): array
678
    {
679
        if ($this->data['type'] !== 'video') {
1✔
UNCOV
680
            throw new RuntimeException(\sprintf('Unable to get video infos of "%s".', $this->data['path']));
×
681
        }
682

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

685
        return [
1✔
686
            'duration' => $video['playtime_seconds'],
1✔
687
            'width'    => $video['video']['resolution_x'],
1✔
688
            'height'   => $video['video']['resolution_y'],
1✔
689
        ];
1✔
690
    }
691

692
    /**
693
     * Builds a relative path from a URL.
694
     * Used for remote files.
695
     */
696
    public static function buildPathFromUrl(string $url): string
697
    {
698
        $host = parse_url($url, PHP_URL_HOST);
1✔
699
        $path = parse_url($url, PHP_URL_PATH) ?? '-index.html'; // if URL ends with a domain (e.g., https://example.com), set path to '-index.html' to avoid empty path
1✔
700
        $query = parse_url($url, PHP_URL_QUERY);
1✔
701
        $ext = pathinfo($path, \PATHINFO_EXTENSION);
1✔
702
        // Google Fonts hack
703
        if (Util\Str::endsWith($path, '/css') || Util\Str::endsWith($path, '/css2')) {
1✔
704
            $ext = 'css';
1✔
705
        }
706

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

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

718
    /**
719
     * Add hash to the file name.
720
     */
721
    protected function doFingerprint(): self
722
    {
723
        $hash = hash('xxh128', $this->data['content']);
1✔
724
        $this->data['path'] = preg_replace(
1✔
725
            '/\.' . $this->data['ext'] . '$/m',
1✔
726
            ".$hash." . $this->data['ext'],
1✔
727
            $this->data['path']
1✔
728
        );
1✔
729
        $this->builder->getLogger()->debug(\sprintf('Asset fingerprinted: "%s"', $this->data['path']));
1✔
730

731
        return $this;
1✔
732
    }
733

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

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

809
        return $this;
1✔
810
    }
811

812
    /**
813
     * Minifying a CSS or a JS + cache.
814
     *
815
     * @throws RuntimeException
816
     */
817
    protected function doMinify(): self
818
    {
819
        // compile SCSS files
820
        if ($this->data['ext'] == 'scss') {
1✔
821
            $this->doCompile();
×
822
        }
823
        // abort if already minified
824
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
1✔
825
            return $this;
×
826
        }
827
        // abord if not a CSS or JS file
828
        if (!\in_array($this->data['ext'], ['css', 'js'])) {
1✔
UNCOV
829
            return $this;
×
830
        }
831
        // in debug mode: disable minify to preserve inline source map
832
        if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) {
1✔
UNCOV
833
            return $this;
×
834
        }
835
        switch ($this->data['ext']) {
1✔
836
            case 'css':
1✔
837
                $minifier = new Minify\CSS($this->data['content']);
1✔
838
                break;
1✔
839
            case 'js':
1✔
840
                $minifier = new Minify\JS($this->data['content']);
1✔
841
                break;
1✔
842
            default:
UNCOV
843
                throw new RuntimeException(\sprintf('Unable to minify "%s".', $this->data['path']));
×
844
        }
845
        $this->data['content'] = $minifier->minify();
1✔
846
        $this->data['size'] = \strlen($this->data['content']);
1✔
847

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

850
        return $this;
1✔
851
    }
852

853
    /**
854
     * Returns local file path and updated path, or throw an exception.
855
     * If $fallback path is set, it will be used if the remote file is not found.
856
     *
857
     * Try to locate the file in:
858
     *   (1. remote file)
859
     *   1. assets
860
     *   2. themes/<theme>/assets
861
     *   3. static
862
     *   4. themes/<theme>/static
863
     *
864
     * @throws RuntimeException
865
     */
866
    private function locateFile(string $path, ?string $fallback = null, ?string $userAgent = null): array
867
    {
868
        // remote file
869
        if (Util\File::isRemote($path)) {
1✔
870
            try {
871
                $url = $path;
1✔
872
                $path = Util::joinPath(
1✔
873
                    (string) $this->config->get('assets.target'),
1✔
874
                    self::buildPathFromUrl($url)
1✔
875
                );
1✔
876
                $cache = new Cache($this->builder, 'assets/_remote');
1✔
877
                if (!$cache->has($path)) {
1✔
878
                    $content = $this->getRemoteFileContent($url, $userAgent);
1✔
879
                    $cache->set($path, [
1✔
880
                        'content' => $content,
1✔
881
                        'path'    => $path,
1✔
882
                    ], $this->config->get('cache.assets.remote.ttl'));
1✔
883
                }
884
                return [
1✔
885
                    'file' => $cache->getContentFile($path),
1✔
886
                    'path' => $path,
1✔
887
                ];
1✔
888
            } catch (RuntimeException $e) {
1✔
889
                if (empty($fallback)) {
1✔
UNCOV
890
                    throw new RuntimeException($e->getMessage());
×
891
                }
892
                $path = $fallback;
1✔
893
            }
894
        }
895

896
        // checks in assets/
897
        $file = Util::joinFile($this->config->getAssetsPath(), $path);
1✔
898
        if (Util\File::getFS()->exists($file)) {
1✔
899
            return [
1✔
900
                'file' => $file,
1✔
901
                'path' => $path,
1✔
902
            ];
1✔
903
        }
904

905
        // checks in each themes/<theme>/assets/
906
        foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
907
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
1✔
908
            if (Util\File::getFS()->exists($file)) {
1✔
909
                return [
1✔
910
                    'file' => $file,
1✔
911
                    'path' => $path,
1✔
912
                ];
1✔
913
            }
914
        }
915

916
        // checks in static/
917
        $file = Util::joinFile($this->config->getStaticPath(), $path);
1✔
918
        if (Util\File::getFS()->exists($file)) {
1✔
919
            return [
1✔
920
                'file' => $file,
1✔
921
                'path' => $path,
1✔
922
            ];
1✔
923
        }
924

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

936
        throw new RuntimeException(\sprintf('Unable to locate file "%s".', $path));
1✔
937
    }
938

939
    /**
940
     * Try to get remote file content.
941
     * Returns file content or throw an exception.
942
     *
943
     * @throws RuntimeException
944
     */
945
    private function getRemoteFileContent(string $path, ?string $userAgent = null): string
946
    {
947
        if (!Util\File::isRemoteExists($path)) {
1✔
948
            throw new RuntimeException(\sprintf('Unable to get remote file "%s".', $path));
1✔
949
        }
950
        if (false === $content = Util\File::fileGetContents($path, $userAgent)) {
1✔
UNCOV
951
            throw new RuntimeException(\sprintf('Unable to get content of remote file "%s".', $path));
×
952
        }
953
        if (\strlen($content) <= 1) {
1✔
UNCOV
954
            throw new RuntimeException(\sprintf('Remote file "%s" is empty.', $path));
×
955
        }
956

957
        return $content;
1✔
958
    }
959

960
    /**
961
     * Optimizing $filepath image.
962
     * Returns the new file size.
963
     */
964
    private function optimizeImage(string $filepath, string $path, int $quality): int
965
    {
966
        $message = \sprintf('Asset not optimized: "%s"', $path);
1✔
967
        $sizeBefore = filesize($filepath);
1✔
968
        Optimizer::create($quality)->optimize($filepath);
1✔
969
        $sizeAfter = filesize($filepath);
1✔
970
        if ($sizeAfter < $sizeBefore) {
1✔
UNCOV
971
            $message = \sprintf('Asset optimized: "%s" (%s Ko -> %s Ko)', $path, ceil($sizeBefore / 1000), ceil($sizeAfter / 1000));
×
972
        }
973
        $this->builder->getLogger()->debug($message);
1✔
974

975
        return $sizeAfter;
1✔
976
    }
977

978
    /**
979
     * Returns image size informations.
980
     *
981
     * @see https://www.php.net/manual/function.getimagesize.php
982
     *
983
     * @throws RuntimeException
984
     */
985
    private function getImageSize(): array|false
986
    {
987
        if (!$this->data['type'] == 'image') {
1✔
988
            return false;
×
989
        }
990

991
        try {
992
            if (false === $size = getimagesizefromstring($this->data['content'])) {
1✔
993
                return false;
1✔
994
            }
UNCOV
995
        } catch (\Exception $e) {
×
UNCOV
996
            throw new RuntimeException(\sprintf('Handling asset "%s" failed: "%s".', $this->data['path'], $e->getMessage()));
×
997
        }
998

999
        return $size;
1✔
1000
    }
1001

1002
    /**
1003
     * Builds CDN image URL.
1004
     */
1005
    private function buildImageCdnUrl(): string
1006
    {
1007
        return str_replace(
×
1008
            [
×
1009
                '%account%',
×
1010
                '%image_url%',
×
1011
                '%width%',
×
1012
                '%quality%',
×
1013
                '%format%',
×
1014
            ],
×
1015
            [
×
UNCOV
1016
                $this->config->get('assets.images.cdn.account') ?? '',
×
UNCOV
1017
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical') ?? true]), '/'),
×
UNCOV
1018
                $this->data['width'],
×
UNCOV
1019
                (int) $this->config->get('assets.images.quality'),
×
UNCOV
1020
                $this->data['ext'],
×
UNCOV
1021
            ],
×
UNCOV
1022
            (string) $this->config->get('assets.images.cdn.url')
×
UNCOV
1023
        );
×
1024
    }
1025

1026
    /**
1027
     * Checks if the asset is not missing and is typed as an image.
1028
     *
1029
     * @throws RuntimeException
1030
     */
1031
    private function checkImage(): void
1032
    {
1033
        if ($this->isMissing()) {
1✔
UNCOV
1034
            throw new RuntimeException(\sprintf('Unable to resize "%s": file not found.', $this->data['path']));
×
1035
        }
1036
        if ($this->data['type'] != 'image') {
1✔
UNCOV
1037
            throw new RuntimeException(\sprintf('Unable to resize "%s": not an image.', $this->data['path']));
×
1038
        }
1039
    }
1040

1041
    /**
1042
     * Remove redondant '/thumbnails/<width(xheight)>/' in the path.
1043
     */
1044
    private function deduplicateThumbPath(string $path): string
1045
    {
1046
        // https://regex101.com/r/0r7FMY/1
1047
        $pattern = '/(' . self::IMAGE_THUMB . '\/(\d+){0,1}x(\d+){0,1}\/)(' . self::IMAGE_THUMB . '\/(\d+){0,1}x(\d+){0,1}\/)(.*)/i';
1✔
1048

1049
        if (null === $result = preg_replace($pattern, '$1$7', $path)) {
1✔
UNCOV
1050
            return $path;
×
1051
        }
1052

1053
        return $result;
1✔
1054
    }
1055
}
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