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

Cecilapp / Cecil / 21441511038

28 Jan 2026 02:10PM UTC coverage: 82.613% (+0.03%) from 82.588%
21441511038

push

github

ArnaudLigny
Fix image resize logic for equal dimensions

Adds a check to return the original image if the requested width and height match the current image dimensions, preventing unnecessary processing.

1 of 2 new or added lines in 1 file covered. (50.0%)

23 existing lines in 3 files now uncovered.

3307 of 4003 relevant lines covered (82.61%)

0.83 hits per line

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

79.75
/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(\sprintf('Unable to handle asset "%s".', $paths[$i]), previous: $e);
×
187
                }
188
            }
189
            $cache->set($locateCacheKey, $this->data);
1✔
190
        }
191
        $this->data = $cache->get($locateCacheKey);
1✔
192

193
        // missing
194
        if ($this->data['missing']) {
1✔
195
            return;
1✔
196
        }
197

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

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

257
        if ($this->isImageInCdn()) {
1✔
258
            return $this->buildImageCdnUrl();
×
259
        }
260

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

265
        return $this->data['path'];
1✔
266
    }
267

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

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

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

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

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

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

322
        $this->builder->addToAssetsList($this->data['path']);
1✔
323
    }
324

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

339
        return $this;
1✔
340
    }
341

342
    /**
343
     * Compiles a SCSS + cache.
344
     *
345
     * @throws RuntimeException
346
     */
347
    public function compile(): self
348
    {
349
        $this->cacheTags['compile'] = true;
1✔
350
        $cache = new Cache($this->builder, 'assets');
1✔
351
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
1✔
352
        if (!$cache->has($cacheKey)) {
1✔
353
            $this->doCompile();
1✔
354
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
1✔
355
        }
356
        $this->data = $cache->get($cacheKey);
1✔
357

358
        return $this;
1✔
359
    }
360

361
    /**
362
     * Minifying a CSS or a JS.
363
     */
364
    public function minify(): self
365
    {
366
        $this->cacheTags['minify'] = true;
1✔
367
        $cache = new Cache($this->builder, 'assets');
1✔
368
        $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags);
1✔
369
        if (!$cache->has($cacheKey)) {
1✔
370
            $this->doMinify();
1✔
371
            $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl'));
1✔
372
        }
373
        $this->data = $cache->get($cacheKey);
1✔
374

375
        return $this;
1✔
376
    }
377

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

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

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

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

417
        // if no width and no height, return the original image
418
        if ($width === null && $height === null) {
1✔
419
            return $this;
×
420
        }
421

422
        // if equal with and height, return the original image
423
        if ($width == $this->data['width'] && $height == $this->data['height']) {
1✔
NEW
424
            return $this;
×
425
        }
426

427
        // if the image width or height is already smaller, return the original image
428
        if ($width !== null && $this->data['width'] <= $width && $height === null) {
1✔
429
            return $this;
1✔
430
        }
431
        if ($height !== null && $this->data['height'] <= $height && $width === null) {
1✔
432
            return $this;
×
433
        }
434

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

439
        if ($this->isImageInCdn()) {
1✔
440
            if ($width === null) {
×
441
                $assetResized->data['width'] = round($this->data['width'] / ($this->data['height'] / $height));
×
442
            }
443
            if ($height === null) {
×
444
                $assetResized->data['height'] = round($this->data['height'] / ($this->data['width'] / $width));
×
445
            }
446

447
            return $assetResized; // returns asset with the new dimensions only: CDN do the rest of the job
×
448
        }
449

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

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

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

475
        return $assetResized;
1✔
476
    }
477

478
    /**
479
     * Creates a maskable image (with a padding = 20%).
480
     *
481
     * @throws RuntimeException
482
     */
483
    public function maskable(?int $padding = null): self
484
    {
485
        $this->checkImage();
×
486

487
        if ($padding === null) {
×
488
            $padding = 20; // default padding
×
489
        }
490

491
        $assetMaskable = clone $this;
×
492

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

495
        $cache = new Cache($this->builder, 'assets');
×
496
        $assetMaskable->cacheTags['maskable'] = true;
×
497
        $cacheKey = $cache->createKeyFromAsset($assetMaskable, $assetMaskable->cacheTags);
×
498
        if (!$cache->has($cacheKey)) {
×
499
            $assetMaskable->data['content'] = Image::maskable($assetMaskable, $quality, $padding);
×
500
            $assetMaskable->data['path'] = '/' . Util::joinPath(
×
501
                (string) $this->config->get('assets.target'),
×
502
                'maskable',
×
503
                $assetMaskable->data['path']
×
504
            );
×
505
            $assetMaskable->data['size'] = \strlen($assetMaskable->data['content']);
×
506

507
            $cache->set($cacheKey, $assetMaskable->data, $this->config->get('cache.assets.ttl'));
×
508
            $this->builder->getLogger()->debug(\sprintf('Asset maskabled: "%s"', $assetMaskable->data['path']));
×
509
        }
510
        $assetMaskable->data = $cache->get($cacheKey);
×
511

512
        return $assetMaskable;
×
513
    }
514

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

526
        if ($quality === null) {
1✔
527
            $quality = (int) $this->config->get('assets.images.quality');
1✔
528
        }
529

530
        $asset = clone $this;
1✔
531
        $asset['ext'] = $format;
1✔
532
        $asset->data['subtype'] = "image/$format";
1✔
533

534
        if ($this->isImageInCdn()) {
1✔
535
            return $asset; // returns the asset with the new extension only: CDN do the rest of the job
×
536
        }
537

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

553
        return $asset;
1✔
554
    }
555

556
    /**
557
     * Converts an image asset to WebP format.
558
     *
559
     * @throws RuntimeException
560
     */
561
    public function webp(?int $quality = null): self
562
    {
563
        return $this->convert('webp', $quality);
×
564
    }
565

566
    /**
567
     * Converts an image asset to AVIF format.
568
     *
569
     * @throws RuntimeException
570
     */
571
    public function avif(?int $quality = null): self
572
    {
573
        return $this->convert('avif', $quality);
×
574
    }
575

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

594
        return false;
1✔
595
    }
596

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

613
                return $size[0];
1✔
614
            case 'video':
1✔
615
                return $this->getVideo()['width'];
1✔
616
        }
617

618
        return null;
1✔
619
    }
620

621
    /**
622
     * Returns the height of an image/SVG or a video.
623
     *
624
     * @throws RuntimeException
625
     */
626
    public function getHeight(): ?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->height;
1✔
632
                }
633
                if (false === $size = $this->getImageSize()) {
1✔
634
                    throw new RuntimeException(\sprintf('Unable to get height of "%s".', $this->data['path']));
×
635
                }
636

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

642
        return null;
1✔
643
    }
644

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

657
        return [
1✔
658
            'duration' => $audio->duration,
1✔
659
            'bitrate'  => $audio->bitRate,
1✔
660
            'channel'  => $audio->channel,
1✔
661
        ];
1✔
662
    }
663

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

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

680
        return [
1✔
681
            'duration' => $video['playtime_seconds'],
1✔
682
            'width'    => $video['video']['resolution_x'],
1✔
683
            'height'   => $video['video']['resolution_y'],
1✔
684
        ];
1✔
685
    }
686

687
    /**
688
     * Builds a relative path from a URL.
689
     * Used for remote files.
690
     */
691
    public static function buildPathFromUrl(string $url): string
692
    {
693
        $host = parse_url($url, PHP_URL_HOST);
1✔
694
        $path = parse_url($url, PHP_URL_PATH);
1✔
695
        $query = parse_url($url, PHP_URL_QUERY);
1✔
696
        $ext = pathinfo(parse_url($url, PHP_URL_PATH), \PATHINFO_EXTENSION);
1✔
697

698
        // Google Fonts hack
699
        if (Util\Str::endsWith($path, '/css') || Util\Str::endsWith($path, '/css2')) {
1✔
700
            $ext = 'css';
1✔
701
        }
702

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

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

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

727
        return $this;
1✔
728
    }
729

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

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

805
        return $this;
1✔
806
    }
807

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

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

846
        return $this;
1✔
847
    }
848

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

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

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

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

921
        // checks in each themes/<theme>/static/
922
        foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
923
            $file = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
1✔
924
            if (Util\File::getFS()->exists($file)) {
1✔
925
                return [
1✔
926
                    'file' => $file,
1✔
927
                    'path' => $path,
1✔
928
                ];
1✔
929
            }
930
        }
931

932
        throw new RuntimeException(\sprintf('Unable to locate file "%s".', $path));
1✔
933
    }
934

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

953
        return $content;
1✔
954
    }
955

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

971
        return $sizeAfter;
1✔
972
    }
973

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

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

995
        return $size;
1✔
996
    }
997

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

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

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

1045
        if (null === $result = preg_replace($pattern, '$1$7', $path)) {
1✔
UNCOV
1046
            return $path;
×
1047
        }
1048

1049
        return $result;
1✔
1050
    }
1051
}
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