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

Cecilapp / Cecil / 21832008463

09 Feb 2026 03:51PM UTC coverage: 82.365% (-0.01%) from 82.378%
21832008463

push

github

ArnaudLigny
Merge branch 'master' of https://github.com/Cecilapp/Cecil

3316 of 4026 relevant lines covered (82.36%)

0.82 hits per line

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

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

336
        return $this;
1✔
337
    }
338

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

355
        return $this;
1✔
356
    }
357

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

372
        return $this;
1✔
373
    }
374

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

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

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

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

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

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

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

432
        $assetResized = clone $this;
1✔
433
        $assetResized->data['width'] = $width ?? $this->data['width'];
1✔
434
        $assetResized->data['height'] = $height ?? $this->data['height'];
1✔
435

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

444
            return $assetResized; // returns asset with the new dimensions only: CDN do the rest of the job
×
445
        }
446

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

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

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

472
        return $assetResized;
1✔
473
    }
474

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

484
        if ($padding === null) {
×
485
            $padding = 20; // default padding
×
486
        }
487

488
        $assetMaskable = clone $this;
×
489

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

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

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

509
        return $assetMaskable;
×
510
    }
511

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

523
        if ($quality === null) {
1✔
524
            $quality = (int) $this->config->get('assets.images.quality');
1✔
525
        }
526

527
        $asset = clone $this;
1✔
528
        $asset['ext'] = $format;
1✔
529
        $asset->data['subtype'] = "image/$format";
1✔
530

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

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

550
        return $asset;
1✔
551
    }
552

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

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

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

591
        return false;
1✔
592
    }
593

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

610
                return $size[0];
1✔
611
            case 'video':
1✔
612
                return $this->getVideo()['width'];
1✔
613
        }
614

615
        return null;
1✔
616
    }
617

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

634
                return $size[1];
1✔
635
            case 'video':
1✔
636
                return $this->getVideo()['height'];
1✔
637
        }
638

639
        return null;
1✔
640
    }
641

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

654
        return [
1✔
655
            'duration' => $audio->duration,
1✔
656
            'bitrate'  => $audio->bitRate,
1✔
657
            'channel'  => $audio->channel,
1✔
658
        ];
1✔
659
    }
660

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

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

677
        return [
1✔
678
            'duration' => $video['playtime_seconds'],
1✔
679
            'width'    => $video['video']['resolution_x'],
1✔
680
            'height'   => $video['video']['resolution_y'],
1✔
681
        ];
1✔
682
    }
683

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

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

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

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

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

724
        return $this;
1✔
725
    }
726

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

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

802
        return $this;
1✔
803
    }
804

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

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

843
        return $this;
1✔
844
    }
845

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

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

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

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

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

929
        throw new RuntimeException(\sprintf('Unable to locate file "%s".', $path));
1✔
930
    }
931

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

950
        return $content;
1✔
951
    }
952

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

968
        return $sizeAfter;
1✔
969
    }
970

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

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

992
        return $size;
1✔
993
    }
994

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

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

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

1042
        if (null === $result = preg_replace($pattern, '$1$7', $path)) {
1✔
1043
            return $path;
×
1044
        }
1045

1046
        return $result;
1✔
1047
    }
1048
}
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