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

Cecilapp / Cecil / 20029796150

08 Dec 2025 01:29PM UTC coverage: 82.5% (+0.2%) from 82.265%
20029796150

Pull #2258

github

web-flow
Merge 3a315d90c into 1a1309f9c
Pull Request #2258: refactor: Asset()

77 of 86 new or added lines in 2 files covered. (89.53%)

83 existing lines in 1 file now uncovered.

3300 of 4000 relevant lines covered (82.5%)

0.83 hits per line

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

80.49
/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
     *     'leading_slash' => <bool>
60
     *     'ignore_missing' => <bool>,
61
     *     'fingerprint' => <bool>,
62
     *     'minify' => <bool>,
63
     *     'optimize' => <bool>,
64
     *     'fallback' => <string>,
65
     *     'useragent' => <string>,
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 (md5)
1✔
111
        ];
1✔
112

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

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

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

196
        // missing
197
        if ($this->data['missing']) {
1✔
198
            return;
1✔
199
        }
200

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

253
    /**
254
     * Returns path.
255
     */
256
    public function __toString(): string
257
    {
258
        $this->save();
1✔
259

260
        if ($this->isImageInCdn()) {
1✔
261
            return $this->buildImageCdnUrl();
×
262
        }
263

264
        if ($this->builder->getConfig()->isEnabled('canonicalurl')) {
1✔
265
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
×
266
        }
267

268
        return $this->data['path'];
1✔
269
    }
270

271
    /**
272
     * Implements \ArrayAccess.
273
     */
274
    #[\ReturnTypeWillChange]
275
    public function offsetSet($offset, $value): void
276
    {
277
        if (!\is_null($offset)) {
1✔
278
            $this->data[$offset] = $value;
1✔
279
        }
280
    }
281

282
    /**
283
     * Implements \ArrayAccess.
284
     */
285
    #[\ReturnTypeWillChange]
286
    public function offsetExists($offset): bool
287
    {
288
        return isset($this->data[$offset]);
1✔
289
    }
290

291
    /**
292
     * Implements \ArrayAccess.
293
     */
294
    #[\ReturnTypeWillChange]
295
    public function offsetUnset($offset): void
296
    {
NEW
297
        unset($this->data[$offset]);
×
298
    }
299

300
    /**
301
     * Implements \ArrayAccess.
302
     */
303
    #[\ReturnTypeWillChange]
304
    public function offsetGet($offset)
305
    {
306
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
1✔
307
    }
308

309
    /**
310
     * Adds asset path to the list of assets to save.
311
     *
312
     * @throws RuntimeException
313
     */
314
    public function save(): void
315
    {
316
        if ($this->data['missing']) {
1✔
317
            return;
1✔
318
        }
319

320
        $cache = new Cache($this->builder, 'assets');
1✔
321
        if (empty($this->data['path']) || !Util\File::getFS()->exists($cache->getContentFilePathname($this->data['path']))) {
1✔
NEW
322
            throw new RuntimeException(
×
NEW
323
                \sprintf('Unable to add "%s" to assets list. Please clear cache and retry.', $this->data['path'])
×
NEW
324
            );
×
325
        }
326

327
        $this->builder->addAsset($this->data['path']);
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->createKeyFromAsset($this, $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->createKeyFromAsset($this, $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->createKeyFromAsset($this, $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
     * Scales down an image to a new $width.
410
     *
411
     * @throws RuntimeException
412
     */
413
    public function resize(int $width): self
414
    {
415
        $this->checkImage();
1✔
416

417
        // if the image is already smaller than the requested width, return it
418
        if ($width >= $this->data['width']) {
1✔
419
            return $this;
1✔
420
        }
421

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

425
        if ($this->isImageInCdn()) {
1✔
426
            $assetResized->data['height'] = round($this->data['height'] / ($this->data['width'] / $width));
×
427

428
            return $assetResized; // returns asset with the new dimensions only: CDN do the rest of the job
×
429
        }
430

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

433
        $cache = new Cache($this->builder, 'assets');
1✔
434
        $assetResized->cacheTags['quality'] = $quality;
1✔
435
        $assetResized->cacheTags['width'] = $width;
1✔
436
        $cacheKey = $cache->createKeyFromAsset($assetResized, $assetResized->cacheTags);
1✔
437
        if (!$cache->has($cacheKey)) {
1✔
438
            $assetResized->data['content'] = Image::resize($assetResized, $width, $quality);
1✔
439
            $assetResized->data['path'] = '/' . Util::joinPath(
1✔
440
                (string) $this->config->get('assets.target'),
1✔
441
                self::IMAGE_THUMB,
1✔
442
                (string) $width,
1✔
443
                $assetResized->data['path']
1✔
444
            );
1✔
445
            $assetResized->data['path'] = $this->deduplicateThumbPath($assetResized->data['path']);
1✔
446
            $assetResized->data['height'] = $assetResized->getHeight();
1✔
447
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
1✔
448

449
            $cache->set($cacheKey, $assetResized->data, $this->config->get('cache.assets.ttl'));
1✔
450
            $this->builder->getLogger()->debug(\sprintf('Asset resized: "%s" (%sx)', $assetResized->data['path'], $width));
1✔
451
        }
452
        $assetResized->data = $cache->get($cacheKey);
1✔
453

454
        return $assetResized;
1✔
455
    }
456

457
    /**
458
     * Crops the image to the specified width and height, keeping the specified position.
459
     *
460
     * @throws RuntimeException
461
     */
462
    public function cover(int $width, int $height): self
463
    {
464
        $this->checkImage();
1✔
465

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

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

472
        $cache = new Cache($this->builder, 'assets');
1✔
473
        $assetResized->cacheTags['quality'] = $quality;
1✔
474
        $assetResized->cacheTags['width'] = $width;
1✔
475
        $assetResized->cacheTags['height'] = $height;
1✔
476
        $cacheKey = $cache->createKeyFromAsset($assetResized, $assetResized->cacheTags);
1✔
477
        if (!$cache->has($cacheKey)) {
1✔
478
            $assetResized->data['content'] = Image::cover($assetResized, $width, $height, $quality);
1✔
479
            $assetResized->data['path'] = '/' . Util::joinPath(
1✔
480
                (string) $this->config->get('assets.target'),
1✔
481
                self::IMAGE_THUMB,
1✔
482
                (string) $width . 'x' . (string) $height,
1✔
483
                $assetResized->data['path']
1✔
484
            );
1✔
485
            $assetResized->data['path'] = $this->deduplicateThumbPath($assetResized->data['path']);
1✔
486
            $assetResized->data['size'] = \strlen($assetResized->data['content']);
1✔
487

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

493
        return $assetResized;
1✔
494
    }
495

496
    /**
497
     * Creates a maskable image (with a padding = 20%).
498
     *
499
     * @throws RuntimeException
500
     */
501
    public function maskable(?int $padding = null): self
502
    {
503
        $this->checkImage();
×
504

505
        if ($padding === null) {
×
506
            $padding = 20; // default padding
×
507
        }
508

509
        $assetMaskable = clone $this;
×
510

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

513
        $cache = new Cache($this->builder, 'assets');
×
514
        $assetMaskable->cacheTags['maskable'] = true;
×
515
        $cacheKey = $cache->createKeyFromAsset($assetMaskable, $assetMaskable->cacheTags);
×
516
        if (!$cache->has($cacheKey)) {
×
517
            $assetMaskable->data['content'] = Image::maskable($assetMaskable, $quality, $padding);
×
518
            $assetMaskable->data['path'] = '/' . Util::joinPath(
×
519
                (string) $this->config->get('assets.target'),
×
520
                'maskable',
×
521
                $assetMaskable->data['path']
×
522
            );
×
523
            $assetMaskable->data['size'] = \strlen($assetMaskable->data['content']);
×
524

525
            $cache->set($cacheKey, $assetMaskable->data, $this->config->get('cache.assets.ttl'));
×
526
            $this->builder->getLogger()->debug(\sprintf('Asset maskabled: "%s"', $assetMaskable->data['path']));
×
527
        }
528
        $assetMaskable->data = $cache->get($cacheKey);
×
529

530
        return $assetMaskable;
×
531
    }
532

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

544
        if ($quality === null) {
1✔
545
            $quality = (int) $this->config->get('assets.images.quality');
1✔
546
        }
547

548
        $asset = clone $this;
1✔
549
        $asset['ext'] = $format;
1✔
550
        $asset->data['subtype'] = "image/$format";
1✔
551

552
        if ($this->isImageInCdn()) {
1✔
553
            return $asset; // returns the asset with the new extension only: CDN do the rest of the job
×
554
        }
555

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

571
        return $asset;
1✔
572
    }
573

574
    /**
575
     * Converts an image asset to WebP format.
576
     *
577
     * @throws RuntimeException
578
     */
579
    public function webp(?int $quality = null): self
580
    {
581
        return $this->convert('webp', $quality);
×
582
    }
583

584
    /**
585
     * Converts an image asset to AVIF format.
586
     *
587
     * @throws RuntimeException
588
     */
589
    public function avif(?int $quality = null): self
590
    {
591
        return $this->convert('avif', $quality);
×
592
    }
593

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

612
        return false;
1✔
613
    }
614

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

631
                return $size[0];
1✔
632
            case 'video':
1✔
633
                return $this->getVideo()['width'];
1✔
634
        }
635

636
        return null;
1✔
637
    }
638

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

655
                return $size[1];
1✔
656
            case 'video':
1✔
657
                return $this->getVideo()['height'];
1✔
658
        }
659

660
        return null;
1✔
661
    }
662

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

675
        return [
1✔
676
            'duration' => $audio->duration,
1✔
677
            'bitrate'  => $audio->bitRate,
1✔
678
            'channel'  => $audio->channel,
1✔
679
        ];
1✔
680
    }
681

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

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

698
        return [
1✔
699
            'duration' => $video['playtime_seconds'],
1✔
700
            'width'    => $video['video']['resolution_x'],
1✔
701
            'height'   => $video['video']['resolution_y'],
1✔
702
        ];
1✔
703
    }
704

705
    /**
706
     * Builds a relative path from a URL.
707
     * Used for remote files.
708
     */
709
    public static function buildPathFromUrl(string $url): string
710
    {
711
        $host = parse_url($url, PHP_URL_HOST);
1✔
712
        $path = parse_url($url, PHP_URL_PATH);
1✔
713
        $query = parse_url($url, PHP_URL_QUERY);
1✔
714
        $ext = pathinfo(parse_url($url, PHP_URL_PATH), \PATHINFO_EXTENSION);
1✔
715

716
        // Google Fonts hack
717
        if (Util\Str::endsWith($path, '/css') || Util\Str::endsWith($path, '/css2')) {
1✔
718
            $ext = 'css';
1✔
719
        }
720

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

724
    /**
725
     * Replaces some characters by '_'.
726
     */
727
    public static function sanitize(string $string): string
728
    {
729
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
1✔
730
    }
731

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

745
        return $this;
1✔
746
    }
747

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

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

823
        return $this;
1✔
824
    }
825

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

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

864
        return $this;
1✔
865
    }
866

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

906
        // checks in assets/
907
        $file = Util::joinFile($this->config->getAssetsPath(), $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
        // checks in each themes/<theme>/assets/
916
        foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
917
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $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

926
        // checks in static/
927
        $file = Util::joinFile($this->config->getStaticPath(), $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>/static/
936
        foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
937
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
1✔
938
            if (Util\File::getFS()->exists($file)) {
1✔
939
                return [
1✔
940
                    'file' => $file,
1✔
941
                    'path' => $path,
1✔
942
                ];
1✔
943
            }
944
        }
945

946
        throw new RuntimeException(\sprintf('Unable to locate file "%s".', $path));
1✔
947
    }
948

949
    /**
950
     * Try to get remote file content.
951
     * Returns file content or throw an exception.
952
     *
953
     * @throws RuntimeException
954
     */
955
    private function getRemoteFileContent(string $path, ?string $userAgent = null): string
956
    {
957
        if (!Util\File::isRemoteExists($path)) {
1✔
958
            throw new RuntimeException(\sprintf('Unable to get remote file "%s".', $path));
1✔
959
        }
960
        if (false === $content = Util\File::fileGetContents($path, $userAgent)) {
1✔
961
            throw new RuntimeException(\sprintf('Unable to get content of remote file "%s".', $path));
×
962
        }
963
        if (\strlen($content) <= 1) {
1✔
964
            throw new RuntimeException(\sprintf('Remote file "%s" is empty.', $path));
×
965
        }
966

967
        return $content;
1✔
968
    }
969

970
    /**
971
     * Optimizing $filepath image.
972
     * Returns the new file size.
973
     */
974
    private function optimizeImage(string $filepath, string $path, int $quality): int
975
    {
976
        $message = \sprintf('Asset not optimized: "%s"', $path);
1✔
977
        $sizeBefore = filesize($filepath);
1✔
978
        Optimizer::create($quality)->optimize($filepath);
1✔
979
        $sizeAfter = filesize($filepath);
1✔
980
        if ($sizeAfter < $sizeBefore) {
1✔
NEW
981
            $message = \sprintf('Asset optimized: "%s" (%s Ko -> %s Ko)', $path, ceil($sizeBefore / 1000), ceil($sizeAfter / 1000));
×
982
        }
983
        $this->builder->getLogger()->debug($message);
1✔
984

985
        return $sizeAfter;
1✔
986
    }
987

988
    /**
989
     * Returns image size informations.
990
     *
991
     * @see https://www.php.net/manual/function.getimagesize.php
992
     *
993
     * @throws RuntimeException
994
     */
995
    private function getImageSize(): array|false
996
    {
997
        if (!$this->data['type'] == 'image') {
1✔
998
            return false;
×
999
        }
1000

1001
        try {
1002
            if (false === $size = getimagesizefromstring($this->data['content'])) {
1✔
1003
                return false;
1✔
1004
            }
1005
        } catch (\Exception $e) {
×
1006
            throw new RuntimeException(\sprintf('Handling asset "%s" failed: "%s"', $this->data['path'], $e->getMessage()));
×
1007
        }
1008

1009
        return $size;
1✔
1010
    }
1011

1012
    /**
1013
     * Builds CDN image URL.
1014
     */
1015
    private function buildImageCdnUrl(): string
1016
    {
1017
        return str_replace(
×
1018
            [
×
1019
                '%account%',
×
1020
                '%image_url%',
×
1021
                '%width%',
×
1022
                '%quality%',
×
1023
                '%format%',
×
1024
            ],
×
1025
            [
×
1026
                $this->config->get('assets.images.cdn.account') ?? '',
×
1027
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical') ?? true]), '/'),
×
1028
                $this->data['width'],
×
1029
                (int) $this->config->get('assets.images.quality'),
×
1030
                $this->data['ext'],
×
1031
            ],
×
1032
            (string) $this->config->get('assets.images.cdn.url')
×
1033
        );
×
1034
    }
1035

1036
    /**
1037
     * Checks if the asset is not missing and is typed as an image.
1038
     *
1039
     * @throws RuntimeException
1040
     */
1041
    private function checkImage(): void
1042
    {
1043
        if ($this->data['missing']) {
1✔
1044
            throw new RuntimeException(\sprintf('Unable to resize "%s": file not found.', $this->data['path']));
×
1045
        }
1046
        if ($this->data['type'] != 'image') {
1✔
1047
            throw new RuntimeException(\sprintf('Unable to resize "%s": not an image.', $this->data['path']));
×
1048
        }
1049
    }
1050

1051
    /**
1052
     * Remove redondant '/thumbnails/<width(xheight)>/' in the path.
1053
     */
1054
    private function deduplicateThumbPath(string $path): string
1055
    {
1056
        // https://regex101.com/r/1HXJmw/1
1057
        $pattern = '/(' . self::IMAGE_THUMB . '\/\d+(x\d+){0,1}\/)(' . self::IMAGE_THUMB . '\/\d+(x\d+){0,1}\/)(.*)/i';
1✔
1058

1059
        if (null === $result = preg_replace($pattern, '$1$5', $path)) {
1✔
1060
            return $path;
×
1061
        }
1062

1063
        return $result;
1✔
1064
    }
1065
}
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