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

Cecilapp / Cecil / 7142468876

08 Dec 2023 02:20PM UTC coverage: 83.0% (+0.5%) from 82.534%
7142468876

Pull #1676

github

web-flow
Merge 992f2274c into 814daa587
Pull Request #1676: 8.x dev

186 of 231 new or added lines in 31 files covered. (80.52%)

17 existing lines in 6 files now uncovered.

2861 of 3447 relevant lines covered (83.0%)

0.83 hits per line

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

75.28
/src/Assets/Asset.php
1
<?php
2

3
declare(strict_types=1);
4

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

14
namespace Cecil\Assets;
15

16
use Cecil\Assets\Image\Optimizer;
17
use Cecil\Builder;
18
use Cecil\Collection\Page\Page;
19
use Cecil\Config;
20
use Cecil\Exception\RuntimeException;
21
use Cecil\Util;
22
use Intervention\Image\ImageManagerStatic as ImageManager;
23
use MatthiasMullie\Minify;
24
use ScssPhp\ScssPhp\Compiler;
25
use wapmorgan\Mp3Info\Mp3Info;
26

27
class Asset implements \ArrayAccess
28
{
29
    /** @var Builder */
30
    protected $builder;
31

32
    /** @var Config */
33
    protected $config;
34

35
    /** @var array */
36
    protected $data = [];
37

38
    /** @var bool */
39
    protected $fingerprinted = false;
40

41
    /** @var bool */
42
    protected $compiled = false;
43

44
    /** @var bool */
45
    protected $minified = false;
46

47
    /** @var bool */
48
    protected $optimize = false;
49

50
    /** @var bool */
51
    protected $ignore_missing = false;
52

53
    /**
54
     * Creates an Asset from a file path, an array of files path or an URL.
55
     *
56
     * @param Builder      $builder
57
     * @param string|array $paths
58
     * @param array|null   $options e.g.: ['fingerprint' => true, 'minify' => true, 'filename' => '', 'ignore_missing' => false]
59
     *
60
     * @throws RuntimeException
61
     */
62
    public function __construct(Builder $builder, $paths, array $options = null)
63
    {
64
        $this->builder = $builder;
1✔
65
        $this->config = $builder->getConfig();
1✔
66
        $paths = \is_array($paths) ? $paths : [$paths];
1✔
67
        array_walk($paths, function ($path) {
1✔
68
            if (!\is_string($path)) {
1✔
69
                throw new RuntimeException(sprintf('The path to an asset must be a string (%s given).', \gettype($path)));
×
70
            }
71
            if (empty($path)) {
1✔
72
                throw new RuntimeException('The path to an asset can\'t be empty.');
×
73
            }
74
            if (substr($path, 0, 2) == '..') {
1✔
75
                throw new RuntimeException(sprintf('The path to asset "%s" is wrong: it must be directly relative to "assets" or "static" directory, or a remote URL.', $path));
×
76
            }
77
        });
1✔
78
        $this->data = [
1✔
79
            'file'           => '',    // absolute file path
1✔
80
            'files'          => [],    // array of files path (if bundle)
1✔
81
            'filename'       => '',    // filename
1✔
82
            'path_source'    => '',    // public path to the file, before transformations
1✔
83
            'path'           => '',    // public path to the file, after transformations
1✔
84
            'url'            => null,  // URL of a remote image
1✔
85
            'missing'        => false, // if file not found, but missing ollowed 'missing' is true
1✔
86
            'ext'            => '',    // file extension
1✔
87
            'type'           => '',    // file type (e.g.: image, audio, video, etc.)
1✔
88
            'subtype'        => '',    // file media type (e.g.: image/png, audio/mp3, etc.)
1✔
89
            'size'           => 0,     // file size (in bytes)
1✔
90
            'content_source' => '',    // file content, before transformations
1✔
91
            'content'        => '',    // file content, after transformations
1✔
92
            'width'          => 0,     // width (in pixels) in case of an image
1✔
93
            'height'         => 0,     // height (in pixels) in case of an image
1✔
94
            'exif'           => [],    // exif data
1✔
95
        ];
1✔
96

97
        // handles options
98
        $fingerprint = (bool) $this->config->get('assets.fingerprint.enabled');
1✔
99
        $minify = (bool) $this->config->get('assets.minify.enabled');
1✔
100
        $optimize = (bool) $this->config->get('assets.images.optimize.enabled');
1✔
101
        $filename = '';
1✔
102
        $ignore_missing = false;
1✔
103
        $remote_fallback = null;
1✔
104
        $force_slash = true;
1✔
105
        extract(\is_array($options) ? $options : [], EXTR_IF_EXISTS);
1✔
106
        $this->ignore_missing = $ignore_missing;
1✔
107

108
        // fill data array with file(s) informations
109
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
110
        $cacheKey = sprintf('%s__%s', implode('_', $paths), $this->builder->getVersion());
1✔
111
        if (!$cache->has($cacheKey)) {
1✔
112
            $pathsCount = \count($paths);
1✔
113
            $file = [];
1✔
114
            for ($i = 0; $i < $pathsCount; $i++) {
1✔
115
                // loads file(s)
116
                $file[$i] = $this->loadFile($paths[$i], $ignore_missing, $remote_fallback, $force_slash);
1✔
117
                // bundle: same type/ext only
118
                if ($i > 0) {
1✔
119
                    if ($file[$i]['type'] != $file[$i - 1]['type']) {
1✔
120
                        throw new RuntimeException(sprintf('Asset bundle type error (%s != %s).', $file[$i]['type'], $file[$i - 1]['type']));
×
121
                    }
122
                    if ($file[$i]['ext'] != $file[$i - 1]['ext']) {
1✔
123
                        throw new RuntimeException(sprintf('Asset bundle extension error (%s != %s).', $file[$i]['ext'], $file[$i - 1]['ext']));
×
124
                    }
125
                }
126
                // missing allowed = empty path
127
                if ($file[$i]['missing']) {
1✔
128
                    $this->data['missing'] = true;
1✔
129
                    $this->data['path'] = $file[$i]['path'];
1✔
130

131
                    continue;
1✔
132
                }
133
                // set data
134
                $this->data['size'] += $file[$i]['size'];
1✔
135
                $this->data['content_source'] .= $file[$i]['content'];
1✔
136
                $this->data['content'] .= $file[$i]['content'];
1✔
137
                if ($i == 0) {
1✔
138
                    $this->data['file'] = $file[$i]['filepath'];
1✔
139
                    $this->data['filename'] = $file[$i]['path'];
1✔
140
                    $this->data['path_source'] = $file[$i]['path'];
1✔
141
                    $this->data['path'] = $file[$i]['path'];
1✔
142
                    $this->data['url'] = $file[$i]['url'];
1✔
143
                    $this->data['ext'] = $file[$i]['ext'];
1✔
144
                    $this->data['type'] = $file[$i]['type'];
1✔
145
                    $this->data['subtype'] = $file[$i]['subtype'];
1✔
146
                    if ($this->data['type'] == 'image') {
1✔
147
                        $this->data['width'] = $this->getWidth();
1✔
148
                        $this->data['height'] = $this->getHeight();
1✔
149
                        if ($this->data['subtype'] == 'jpeg') {
1✔
150
                            $this->data['exif'] = Util\File::readExif($file[$i]['filepath']);
×
151
                        }
152
                    }
153
                    // bundle: default filename
154
                    if ($pathsCount > 1 && empty($filename)) {
1✔
155
                        switch ($this->data['ext']) {
1✔
156
                            case 'scss':
1✔
157
                            case 'css':
1✔
158
                                $filename = '/styles.css';
1✔
159
                                break;
1✔
160
                            case 'js':
1✔
161
                                $filename = '/scripts.js';
1✔
162
                                break;
1✔
163
                            default:
NEW
164
                                throw new RuntimeException(sprintf('Asset bundle supports "%s" files only.', '.scss, .css and .js'));
×
165
                        }
166
                    }
167
                    // bundle: filename and path
168
                    if (!empty($filename)) {
1✔
169
                        $this->data['filename'] = $filename;
1✔
170
                        $this->data['path'] = '/' . ltrim($filename, '/');
1✔
171
                    }
172
                }
173
                // bundle: files path
174
                $this->data['files'][] = $file[$i]['filepath'];
1✔
175
            }
176
            // bundle: define path
177
            if ($pathsCount > 1 && empty($filename)) {
1✔
178
                switch ($this->data['ext']) {
×
179
                    case 'scss':
×
180
                    case 'css':
×
181
                        $this->data['path'] = '/styles.' . $file[0]['ext'];
×
182
                        break;
×
183
                    case 'js':
×
184
                        $this->data['path'] = '/scripts.' . $file[0]['ext'];
×
185
                        break;
×
186
                    default:
187
                        throw new RuntimeException(sprintf('Asset bundle supports "%s" files only.', '.scss, .css and .js'));
×
188
                }
189
            }
190
            $cache->set($cacheKey, $this->data);
1✔
191
        }
192
        $this->data = $cache->get($cacheKey);
1✔
193

194
        // fingerprinting
195
        if ($fingerprint) {
1✔
196
            $this->fingerprint();
1✔
197
        }
198
        // compiling (Sass files)
199
        if ((bool) $this->config->get('assets.compile.enabled')) {
1✔
200
            $this->compile();
1✔
201
        }
202
        // minifying (CSS and JavScript files)
203
        if ($minify) {
1✔
204
            $this->minify();
1✔
205
        }
206
        // optimizing (images files)
207
        if ($optimize) {
1✔
208
            $this->optimize = true;
1✔
209
        }
210
    }
211

212
    /**
213
     * Returns path.
214
     *
215
     * @throws RuntimeException
216
     */
217
    public function __toString(): string
218
    {
219
        try {
220
            $this->save();
1✔
221
        } catch (\Exception $e) {
×
222
            $this->builder->getLogger()->error($e->getMessage());
×
223
        }
224

225
        if ($this->isImageInCdn()) {
1✔
226
            return $this->buildImageCdnUrl();
×
227
        }
228

229
        if ($this->builder->getConfig()->get('canonicalurl')) {
1✔
230
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
×
231
        }
232

233
        return $this->data['path'];
1✔
234
    }
235

236
    /**
237
     * Fingerprints a file.
238
     */
239
    public function fingerprint(): self
240
    {
241
        if ($this->fingerprinted) {
1✔
242
            return $this;
1✔
243
        }
244

245
        $fingerprint = hash('md5', $this->data['content_source']);
1✔
246
        $this->data['path'] = preg_replace(
1✔
247
            '/\.' . $this->data['ext'] . '$/m',
1✔
248
            ".$fingerprint." . $this->data['ext'],
1✔
249
            $this->data['path']
1✔
250
        );
1✔
251

252
        $this->fingerprinted = true;
1✔
253

254
        return $this;
1✔
255
    }
256

257
    /**
258
     * Compiles a SCSS.
259
     *
260
     * @throws RuntimeException
261
     */
262
    public function compile(): self
263
    {
264
        if ($this->compiled) {
1✔
265
            return $this;
1✔
266
        }
267

268
        if ($this->data['ext'] != 'scss') {
1✔
269
            return $this;
1✔
270
        }
271

272
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
273
        $cacheKey = $cache->createKeyFromAsset($this, ['compiled']);
1✔
274
        if (!$cache->has($cacheKey)) {
1✔
275
            $scssPhp = new Compiler();
1✔
276
            $importDir = [];
1✔
277
            $importDir[] = Util::joinPath($this->config->getStaticPath());
1✔
278
            $importDir[] = Util::joinPath($this->config->getAssetsPath());
1✔
279
            $scssDir = $this->config->get('assets.compile.import') ?? [];
1✔
280
            $themes = $this->config->getTheme() ?? [];
1✔
281
            foreach ($scssDir as $dir) {
1✔
282
                $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir);
1✔
283
                $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir);
1✔
284
                $importDir[] = Util::joinPath(\dirname($this->data['file']), $dir);
1✔
285
                foreach ($themes as $theme) {
1✔
286
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir"));
1✔
287
                    $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir"));
1✔
288
                }
289
            }
290
            $scssPhp->setImportPaths(array_unique($importDir));
1✔
291
            // source map
292
            if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) {
1✔
293
                $importDir = [];
×
294
                $assetDir = (string) $this->config->get('assets.dir');
×
295
                $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR . $assetDir . DIRECTORY_SEPARATOR);
×
296
                $fileRelPath = substr($this->data['file'], $assetDirPos + 8);
×
297
                $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath);
×
298
                $importDir[] = \dirname($filePath);
×
299
                foreach ($scssDir as $dir) {
×
300
                    $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir);
×
301
                }
302
                $scssPhp->setImportPaths(array_unique($importDir));
×
303
                $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE);
×
304
                $scssPhp->setSourceMapOptions([
×
305
                    'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()),
×
306
                    'sourceRoot'        => '/',
×
307
                ]);
×
308
            }
309
            // output style
310
            $outputStyles = ['expanded', 'compressed'];
1✔
311
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
1✔
312
            if (!\in_array($outputStyle, $outputStyles)) {
1✔
313
                throw new RuntimeException(sprintf('Scss output style "%s" doesn\'t exists.', $outputStyle));
×
314
            }
315
            $scssPhp->setOutputStyle($outputStyle);
1✔
316
            // variables
317
            $variables = $this->config->get('assets.compile.variables') ?? [];
1✔
318
            if (!empty($variables)) {
1✔
319
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
1✔
320
                $scssPhp->replaceVariables($variables);
1✔
321
            }
322
            // update data
323
            $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']);
1✔
324
            $this->data['ext'] = 'css';
1✔
325
            $this->data['type'] = 'text';
1✔
326
            $this->data['subtype'] = 'text/css';
1✔
327
            $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss();
1✔
328
            $this->data['size'] = \strlen($this->data['content']);
1✔
329
            $this->compiled = true;
1✔
330
            $cache->set($cacheKey, $this->data);
1✔
331
        }
332
        $this->data = $cache->get($cacheKey);
1✔
333

334
        return $this;
1✔
335
    }
336

337
    /**
338
     * Minifying a CSS or a JS.
339
     *
340
     * @throws RuntimeException
341
     */
342
    public function minify(): self
343
    {
344
        // disable minify to preserve inline source map
345
        if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) {
1✔
346
            return $this;
×
347
        }
348

349
        if ($this->minified) {
1✔
350
            return $this;
×
351
        }
352

353
        if ($this->data['ext'] == 'scss') {
1✔
354
            $this->compile();
×
355
        }
356

357
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
1✔
UNCOV
358
            return $this;
×
359
        }
360

361
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
1✔
UNCOV
362
            $this->minified;
×
363

UNCOV
364
            return $this;
×
365
        }
366

367
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
368
        $cacheKey = $cache->createKeyFromAsset($this, ['minified']);
1✔
369
        if (!$cache->has($cacheKey)) {
1✔
370
            switch ($this->data['ext']) {
1✔
371
                case 'css':
1✔
372
                    $minifier = new Minify\CSS($this->data['content']);
1✔
373
                    break;
1✔
374
                case 'js':
1✔
375
                    $minifier = new Minify\JS($this->data['content']);
1✔
376
                    break;
1✔
377
                default:
378
                    throw new RuntimeException(sprintf('Not able to minify "%s"', $this->data['path']));
×
379
            }
380
            $this->data['path'] = preg_replace(
1✔
381
                '/\.' . $this->data['ext'] . '$/m',
1✔
382
                '.min.' . $this->data['ext'],
1✔
383
                $this->data['path']
1✔
384
            );
1✔
385
            $this->data['content'] = $minifier->minify();
1✔
386
            $this->data['size'] = \strlen($this->data['content']);
1✔
387
            $this->minified = true;
1✔
388
            $cache->set($cacheKey, $this->data);
1✔
389
        }
390
        $this->data = $cache->get($cacheKey);
1✔
391

392
        return $this;
1✔
393
    }
394

395
    /**
396
     * Optimizing an image.
397
     */
398
    public function optimize(string $filepath): self
399
    {
400
        if ($this->data['type'] != 'image') {
1✔
401
            return $this;
1✔
402
        }
403

404
        $quality = $this->config->get('assets.images.quality') ?? 75;
1✔
405
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
406
        $tags = ["q$quality", 'optimized'];
1✔
407
        if ($this->data['width']) {
1✔
408
            array_unshift($tags, "{$this->data['width']}x");
1✔
409
        }
410
        $cacheKey = $cache->createKeyFromAsset($this, $tags);
1✔
411
        if (!$cache->has($cacheKey)) {
1✔
412
            $message = $this->data['path'];
1✔
413
            $sizeBefore = filesize($filepath);
1✔
414
            Optimizer::create($quality)->optimize($filepath);
1✔
415
            $sizeAfter = filesize($filepath);
1✔
416
            if ($sizeAfter < $sizeBefore) {
1✔
417
                $message = sprintf(
×
418
                    '%s (%s Ko -> %s Ko)',
×
419
                    $message,
×
420
                    ceil($sizeBefore / 1000),
×
421
                    ceil($sizeAfter / 1000)
×
422
                );
×
423
            }
424
            $this->data['content'] = Util\File::fileGetContents($filepath);
1✔
425
            $this->data['size'] = $sizeAfter;
1✔
426
            $cache->set($cacheKey, $this->data);
1✔
427
            $this->builder->getLogger()->debug(sprintf('Asset "%s" optimized', $message));
1✔
428
        }
429
        $this->data = $cache->get($cacheKey, $this->data);
1✔
430

431
        return $this;
1✔
432
    }
433

434
    /**
435
     * Resizes an image with a new $width.
436
     *
437
     * @throws RuntimeException
438
     */
439
    public function resize(int $width): self
440
    {
441
        if ($this->data['missing']) {
1✔
442
            throw new RuntimeException(sprintf('Not able to resize "%s": file not found', $this->data['path']));
×
443
        }
444
        if ($this->data['type'] != 'image') {
1✔
445
            throw new RuntimeException(sprintf('Not able to resize "%s": not an image', $this->data['path']));
×
446
        }
447
        if ($width >= $this->data['width']) {
1✔
448
            return $this;
1✔
449
        }
450

451
        $assetResized = clone $this;
1✔
452
        $assetResized->data['width'] = $width;
1✔
453

454
        if ($this->isImageInCdn()) {
1✔
455
            return $assetResized; // returns the asset with the new width only: CDN do the rest of the job
×
456
        }
457

458
        $quality = $this->config->get('assets.images.quality');
1✔
459
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
460
        $cacheKey = $cache->createKeyFromAsset($assetResized, ["{$width}x", "q$quality"]);
1✔
461
        if (!$cache->has($cacheKey)) {
1✔
462
            if ($assetResized->data['type'] !== 'image') {
1✔
463
                throw new RuntimeException(sprintf('Not able to resize "%s"', $assetResized->data['path']));
×
464
            }
465
            if (!\extension_loaded('gd')) {
1✔
466
                throw new RuntimeException('GD extension is required to use images resize.');
×
467
            }
468

469
            try {
470
                $img = ImageManager::make($assetResized->data['content_source'])->encode($assetResized->data['ext']);
1✔
471
                $img->resize($width, null, function (\Intervention\Image\Constraint $constraint) {
1✔
472
                    $constraint->aspectRatio();
1✔
473
                    $constraint->upsize();
1✔
474
                });
1✔
475
            } catch (\Exception $e) {
×
476
                throw new RuntimeException(sprintf('Not able to resize image "%s": %s', $assetResized->data['path'], $e->getMessage()));
×
477
            }
478
            $assetResized->data['path'] = '/' . Util::joinPath(
1✔
479
                (string) $this->config->get('assets.target'),
1✔
480
                (string) $this->config->get('assets.images.resize.dir'),
1✔
481
                (string) $width,
1✔
482
                $assetResized->data['path']
1✔
483
            );
1✔
484

485
            try {
486
                if ($assetResized->data['subtype'] == 'image/jpeg') {
1✔
487
                    $img->interlace();
×
488
                }
489
                $assetResized->data['content'] = (string) $img->encode($assetResized->data['ext'], $quality);
1✔
490
                $img->destroy();
1✔
491
                $assetResized->data['height'] = $assetResized->getHeight();
1✔
492
                $assetResized->data['size'] = \strlen($assetResized->data['content']);
1✔
493
            } catch (\Exception $e) {
×
494
                throw new RuntimeException(sprintf('Not able to encode image "%s": %s', $assetResized->data['path'], $e->getMessage()));
×
495
            }
496

497
            $cache->set($cacheKey, $assetResized->data);
1✔
498
        }
499
        $assetResized->data = $cache->get($cacheKey);
1✔
500

501
        return $assetResized;
1✔
502
    }
503

504
    /**
505
     * Converts an image asset to WebP format.
506
     *
507
     * @throws RuntimeException
508
     */
509
    public function webp(?int $quality = null): self
510
    {
511
        if ($this->data['type'] !== 'image') {
1✔
512
            throw new RuntimeException(sprintf('can\'t convert "%s" (%s) to WebP: it\'s not an image file.', $this->data['path'], $this->data['type']));
×
513
        }
514

515
        if ($quality === null) {
1✔
516
            $quality = (int) $this->config->get('assets.images.quality') ?? 75;
1✔
517
        }
518

519
        $assetWebp = clone $this;
1✔
520
        $format = 'webp';
1✔
521
        $assetWebp['ext'] = $format;
1✔
522

523
        if ($this->isImageInCdn()) {
1✔
524
            return $assetWebp; // returns the asset with the new extension ('webp') only: CDN do the rest of the job
×
525
        }
526

527
        $img = ImageManager::make($assetWebp['content']);
1✔
528
        $assetWebp['content'] = (string) $img->encode($format, $quality);
1✔
529
        $img->destroy();
1✔
530
        $assetWebp['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']);
1✔
531
        $assetWebp['subtype'] = "image/$format";
1✔
532
        $assetWebp['size'] = \strlen($assetWebp['content']);
1✔
533

534
        return $assetWebp;
1✔
535
    }
536

537
    /**
538
     * Implements \ArrayAccess.
539
     */
540
    #[\ReturnTypeWillChange]
541
    public function offsetSet($offset, $value): void
542
    {
543
        if (!\is_null($offset)) {
1✔
544
            $this->data[$offset] = $value;
1✔
545
        }
546
    }
547

548
    /**
549
     * Implements \ArrayAccess.
550
     */
551
    #[\ReturnTypeWillChange]
552
    public function offsetExists($offset): bool
553
    {
554
        return isset($this->data[$offset]);
1✔
555
    }
556

557
    /**
558
     * Implements \ArrayAccess.
559
     */
560
    #[\ReturnTypeWillChange]
561
    public function offsetUnset($offset): void
562
    {
563
        unset($this->data[$offset]);
×
564
    }
565

566
    /**
567
     * Implements \ArrayAccess.
568
     */
569
    #[\ReturnTypeWillChange]
570
    public function offsetGet($offset)
571
    {
572
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
1✔
573
    }
574

575
    /**
576
     * Hashing content of an asset with the specified algo, sha384 by default.
577
     * Used for SRI (Subresource Integrity).
578
     *
579
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
580
     */
581
    public function getIntegrity(string $algo = 'sha384'): string
582
    {
583
        return sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
1✔
584
    }
585

586
    /**
587
     * Returns MP3 file infos.
588
     *
589
     * @see https://github.com/wapmorgan/Mp3Info
590
     */
591
    public function getAudio(): Mp3Info
592
    {
593
        if ($this->data['type'] !== 'audio') {
1✔
594
            throw new RuntimeException(sprintf('Not able to get audio infos of "%s"', $this->data['path']));
×
595
        }
596

597
        return new Mp3Info($this->data['file']);
1✔
598
    }
599

600
    /**
601
     * Returns MP4 file infos.
602
     *
603
     * @see https://github.com/clwu88/php-read-mp4info
604
     */
605
    public function getVideo(): array
606
    {
607
        if ($this->data['type'] !== 'video') {
×
608
            throw new RuntimeException(sprintf('Not able to get video infos of "%s"', $this->data['path']));
×
609
        }
610

611
        return \Clwu\Mp4::getInfo($this->data['file']);
×
612
    }
613

614
    /**
615
     * Returns the data URL (encoded in Base64).
616
     *
617
     * @throws RuntimeException
618
     */
619
    public function dataurl(): string
620
    {
621
        if ($this->data['type'] == 'image' && !$this->isSVG()) {
1✔
622
            return (string) ImageManager::make($this->data['content'])->encode('data-url', $this->config->get('assets.images.quality'));
1✔
623
        }
624

625
        return sprintf('data:%s;base64,%s', $this->data['subtype'], base64_encode($this->data['content']));
1✔
626
    }
627

628
    /**
629
     * Saves file.
630
     * Note: a file from `static/` with the same name will NOT be overridden.
631
     *
632
     * @throws RuntimeException
633
     */
634
    public function save(): void
635
    {
636
        $filepath = Util::joinFile($this->config->getOutputPath(), $this->data['path']);
1✔
637
        if (!$this->builder->getBuildOptions()['dry-run'] && !Util\File::getFS()->exists($filepath)) {
1✔
638
            try {
639
                Util\File::getFS()->dumpFile($filepath, $this->data['content']);
1✔
640
                $this->builder->getLogger()->debug(sprintf('Asset "%s" saved', $filepath));
1✔
641
                if ($this->optimize) {
1✔
642
                    $this->optimize($filepath);
1✔
643
                }
644
            } catch (\Symfony\Component\Filesystem\Exception\IOException $e) {
×
645
                if (!$this->ignore_missing) {
×
646
                    throw new RuntimeException(sprintf('Can\'t save asset "%s"', $filepath));
×
647
                }
648
            }
649
        }
650
    }
651

652
    /**
653
     * Is Asset is an image in CDN.
654
     *
655
     * @return bool
656
     */
657
    public function isImageInCdn()
658
    {
659
        if ($this->data['type'] != 'image' || (bool) $this->config->get('assets.images.cdn.enabled') !== true || ($this->isSVG() && (bool) $this->config->get('assets.images.cdn.svg') !== true)) {
1✔
660
            return false;
1✔
661
        }
662
        // remote image?
663
        if ($this->data['url'] !== null && (bool) $this->config->get('assets.images.cdn.remote') !== true) {
×
664
            return false;
×
665
        }
666

667
        return true;
×
668
    }
669

670
    /**
671
     * Load file data.
672
     *
673
     * @throws RuntimeException
674
     */
675
    private function loadFile(string $path, bool $ignore_missing = false, ?string $remote_fallback = null, bool $force_slash = true): array
676
    {
677
        $file = [
1✔
678
            'url' => null,
1✔
679
        ];
1✔
680

681
        try {
682
            $filePath = $this->findFile($path, $remote_fallback);
1✔
683
        } catch (\Exception $e) {
1✔
684
            if ($ignore_missing) {
1✔
685
                $file['path'] = $path;
1✔
686
                $file['missing'] = true;
1✔
687

688
                return $file;
1✔
689
            }
690

NEW
691
            throw new RuntimeException(sprintf('Can\'t load asset file "%s" (%s)', $path, $e->getMessage()));
×
692
        }
693

694
        if (Util\Url::isUrl($path)) {
1✔
695
            $file['url'] = $path;
1✔
696
            $path = Util::joinPath(
1✔
697
                (string) $this->config->get('assets.target'),
1✔
698
                Util\File::getFS()->makePathRelative($filePath, $this->config->getCacheAssetsRemotePath())
1✔
699
            );
1✔
700
            // remote_fallback in assets/ ont in cache/assets/remote/
701
            if (substr(Util\File::getFS()->makePathRelative($filePath, $this->config->getCacheAssetsRemotePath()), 0, 2) == '..') {
1✔
NEW
702
                $path = Util::joinPath(
×
NEW
703
                    (string) $this->config->get('assets.target'),
×
NEW
704
                    Util\File::getFS()->makePathRelative($filePath, $this->config->getAssetsPath())
×
NEW
705
                );
×
706
            }
707
            $force_slash = true;
1✔
708
        }
709
        if ($force_slash) {
1✔
710
            $path = '/' . ltrim($path, '/');
1✔
711
        }
712

713
        list($type, $subtype) = Util\File::getMimeType($filePath);
1✔
714
        $content = Util\File::fileGetContents($filePath);
1✔
715

716
        $file['filepath'] = $filePath;
1✔
717
        $file['path'] = $path;
1✔
718
        $file['ext'] = pathinfo($path)['extension'] ?? '';
1✔
719
        $file['type'] = $type;
1✔
720
        $file['subtype'] = $subtype;
1✔
721
        $file['size'] = filesize($filePath);
1✔
722
        $file['content'] = $content;
1✔
723
        $file['missing'] = false;
1✔
724

725
        return $file;
1✔
726
    }
727

728
    /**
729
     * Try to find the file:
730
     *   1. remote (if $path is a valid URL)
731
     *   2. in static/
732
     *   3. in themes/<theme>/static/
733
     * Returns local file path or throw an exception.
734
     *
735
     * @throws RuntimeException
736
     */
737
    private function findFile(string $path, ?string $remote_fallback = null): string
738
    {
739
        // in case of remote file: save it and returns cached file path
740
        if (Util\Url::isUrl($path)) {
1✔
741
            $url = $path;
1✔
742
            $urlHost = parse_url($path, PHP_URL_HOST);
1✔
743
            $urlPath = parse_url($path, PHP_URL_PATH);
1✔
744
            $urlQuery = parse_url($path, PHP_URL_QUERY);
1✔
745
            $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
1✔
746
            // Google Fonts hack
747
            if (Util\Str::endsWith($urlPath, '/css') || Util\Str::endsWith($urlPath, '/css2')) {
1✔
748
                $extension = 'css';
1✔
749
            }
750
            $relativePath = Page::slugify(sprintf(
1✔
751
                '%s%s%s%s',
1✔
752
                $urlHost,
1✔
753
                $this->sanitize($urlPath),
1✔
754
                $urlQuery ? "-$urlQuery" : '',
1✔
755
                $urlQuery && $extension ? ".$extension" : ''
1✔
756
            ));
1✔
757
            $filePath = Util::joinFile($this->config->getCacheAssetsRemotePath(), $relativePath);
1✔
758
            // not already in cache
759
            if (!file_exists($filePath)) {
1✔
760
                try {
761
                    if (!Util\Url::isRemoteFileExists($url)) {
1✔
NEW
762
                        throw new RuntimeException(sprintf('File "%s" doesn\'t exists', $url));
×
763
                    }
764
                    if (false === $content = Util\File::fileGetContents($url, true)) {
1✔
NEW
765
                        throw new RuntimeException(sprintf('Can\'t get content of file "%s"', $url));
×
766
                    }
767
                    if (\strlen($content) <= 1) {
1✔
768
                        throw new RuntimeException(sprintf('File "%s" is empty', $url));
1✔
769
                    }
NEW
770
                } catch (RuntimeException $e) {
×
771
                    // is there a fallback in assets/
772
                    if ($remote_fallback) {
×
773
                        $filePath = Util::joinFile($this->config->getAssetsPath(), $remote_fallback);
×
774
                        if (Util\File::getFS()->exists($filePath)) {
×
775
                            return $filePath;
×
776
                        }
NEW
777
                        throw new RuntimeException(sprintf('Fallback file "%s" doesn\'t exists', $filePath));
×
778
                    }
779

NEW
780
                    throw new RuntimeException($e->getMessage());
×
781
                }
782
                if (false === $content = Util\File::fileGetContents($url, true)) {
1✔
NEW
783
                    throw new RuntimeException(sprintf('Can\'t get content of "%s"', $url));
×
784
                }
785
                if (\strlen($content) <= 1) {
1✔
786
                    throw new RuntimeException(sprintf('Asset at "%s" is empty', $url));
×
787
                }
788
                // put file in cache
789
                Util\File::getFS()->dumpFile($filePath, $content);
1✔
790
            }
791

792
            return $filePath;
1✔
793
        }
794

795
        // checks in assets/
796
        $filePath = Util::joinFile($this->config->getAssetsPath(), $path);
1✔
797
        if (Util\File::getFS()->exists($filePath)) {
1✔
798
            return $filePath;
1✔
799
        }
800

801
        // checks in each themes/<theme>/assets/
802
        foreach ($this->config->getTheme() as $theme) {
1✔
803
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
1✔
804
            if (Util\File::getFS()->exists($filePath)) {
1✔
805
                return $filePath;
1✔
806
            }
807
        }
808

809
        // checks in static/
810
        $filePath = Util::joinFile($this->config->getStaticTargetPath(), $path);
1✔
811
        if (Util\File::getFS()->exists($filePath)) {
1✔
812
            return $filePath;
1✔
813
        }
814

815
        // checks in each themes/<theme>/static/
816
        foreach ($this->config->getTheme() as $theme) {
1✔
817
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
1✔
818
            if (Util\File::getFS()->exists($filePath)) {
1✔
819
                return $filePath;
1✔
820
            }
821
        }
822

823
        throw new RuntimeException(sprintf('Can\'t find file "%s"', $path));
1✔
824
    }
825

826
    /**
827
     * Returns the width of an image/SVG.
828
     *
829
     * @throws RuntimeException
830
     */
831
    private function getWidth(): int
832
    {
833
        if ($this->data['type'] != 'image') {
1✔
834
            return 0;
×
835
        }
836
        if ($this->isSVG() && false !== $svg = $this->getSvgAttributes()) {
1✔
837
            return (int) $svg->width;
1✔
838
        }
839
        if (false === $size = $this->getImageSize()) {
1✔
840
            throw new RuntimeException(sprintf('Not able to get width of "%s"', $this->data['path']));
×
841
        }
842

843
        return $size[0];
1✔
844
    }
845

846
    /**
847
     * Returns the height of an image/SVG.
848
     *
849
     * @throws RuntimeException
850
     */
851
    private function getHeight(): int
852
    {
853
        if ($this->data['type'] != 'image') {
1✔
854
            return 0;
×
855
        }
856
        if ($this->isSVG() && false !== $svg = $this->getSvgAttributes()) {
1✔
857
            return (int) $svg->height;
1✔
858
        }
859
        if (false === $size = $this->getImageSize()) {
1✔
860
            throw new RuntimeException(sprintf('Not able to get height of "%s"', $this->data['path']));
×
861
        }
862

863
        return $size[1];
1✔
864
    }
865

866
    /**
867
     * Returns image size informations.
868
     *
869
     * @see https://www.php.net/manual/function.getimagesize.php
870
     *
871
     * @return array|false
872
     */
873
    private function getImageSize()
874
    {
875
        if (!$this->data['type'] == 'image') {
1✔
876
            return false;
×
877
        }
878

879
        try {
880
            if (false === $size = getimagesizefromstring($this->data['content'])) {
1✔
881
                return false;
1✔
882
            }
883
        } catch (\Exception $e) {
×
884
            throw new RuntimeException(sprintf('Handling asset "%s" failed: "%s"', $this->data['path_source'], $e->getMessage()));
×
885
        }
886

887
        return $size;
1✔
888
    }
889

890
    /**
891
     * Returns true if asset is a SVG.
892
     */
893
    private function isSVG(): bool
894
    {
895
        return \in_array($this->data['subtype'], ['image/svg', 'image/svg+xml']) || $this->data['ext'] == 'svg';
1✔
896
    }
897

898
    /**
899
     * Returns SVG attributes.
900
     *
901
     * @return \SimpleXMLElement|false
902
     */
903
    private function getSvgAttributes()
904
    {
905
        if (false === $xml = simplexml_load_string($this->data['content_source'])) {
1✔
906
            return false;
×
907
        }
908

909
        return $xml->attributes();
1✔
910
    }
911

912
    /**
913
     * Replaces some characters by '_'.
914
     */
915
    private function sanitize(string $string): string
916
    {
917
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
1✔
918
    }
919

920
    /**
921
     * Builds CDN image URL.
922
     */
923
    private function buildImageCdnUrl(): string
924
    {
925
        return str_replace(
×
926
            [
×
927
                '%account%',
×
928
                '%image_url%',
×
929
                '%width%',
×
930
                '%quality%',
×
931
                '%format%',
×
932
            ],
×
933
            [
×
934
                $this->config->get('assets.images.cdn.account'),
×
935
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical') ?? true]), '/'),
×
936
                $this->data['width'],
×
937
                $this->config->get('assets.images.quality') ?? 75,
×
938
                $this->data['ext'],
×
939
            ],
×
940
            (string) $this->config->get('assets.images.cdn.url')
×
941
        );
×
942
    }
943
}
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