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

Cecilapp / Cecil / 7168486434

11 Dec 2023 01:57PM UTC coverage: 83.362% (+0.3%) from 83.077%
7168486434

push

github

ArnaudLigny
refactor: PHP 8 Exception

4 of 17 new or added lines in 8 files covered. (23.53%)

105 existing lines in 2 files now uncovered.

2866 of 3438 relevant lines covered (83.36%)

0.83 hits per line

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

76.75
/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 of an asset must be a string ("%s" given).', \gettype($path)));
×
70
            }
71
            if (empty($path)) {
1✔
72
                throw new RuntimeException('The path of an asset can\'t be empty.');
×
73
            }
74
            if (substr($path, 0, 2) == '..') {
1✔
75
                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));
×
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', $filename ?: 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:
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
            $cache->set($cacheKey, $this->data);
1✔
177
        }
178
        $this->data = $cache->get($cacheKey);
1✔
179

180
        // fingerprinting
181
        if ($fingerprint) {
1✔
182
            $this->fingerprint();
1✔
183
        }
184
        // compiling (Sass files)
185
        if ((bool) $this->config->get('assets.compile.enabled')) {
1✔
186
            $this->compile();
1✔
187
        }
188
        // minifying (CSS and JavScript files)
189
        if ($minify) {
1✔
190
            $this->minify();
1✔
191
        }
192
        // optimizing (images files)
193
        if ($optimize) {
1✔
194
            $this->optimize = true;
1✔
195
        }
196
    }
197

198
    /**
199
     * Returns path.
200
     *
201
     * @throws RuntimeException
202
     */
203
    public function __toString(): string
204
    {
205
        try {
206
            $this->save();
1✔
NEW
207
        } catch (RuntimeException $e) {
×
UNCOV
208
            $this->builder->getLogger()->error($e->getMessage());
×
209
        }
210

211
        if ($this->isImageInCdn()) {
1✔
UNCOV
212
            return $this->buildImageCdnUrl();
×
213
        }
214

215
        if ($this->builder->getConfig()->get('canonicalurl')) {
1✔
UNCOV
216
            return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]);
×
217
        }
218

219
        return $this->data['path'];
1✔
220
    }
221

222
    /**
223
     * Fingerprints a file.
224
     */
225
    public function fingerprint(): self
226
    {
227
        if ($this->fingerprinted) {
1✔
228
            return $this;
1✔
229
        }
230

231
        $fingerprint = hash('md5', $this->data['content_source']);
1✔
232
        $this->data['path'] = preg_replace(
1✔
233
            '/\.' . $this->data['ext'] . '$/m',
1✔
234
            ".$fingerprint." . $this->data['ext'],
1✔
235
            $this->data['path']
1✔
236
        );
1✔
237

238
        $this->fingerprinted = true;
1✔
239

240
        return $this;
1✔
241
    }
242

243
    /**
244
     * Compiles a SCSS.
245
     *
246
     * @throws RuntimeException
247
     */
248
    public function compile(): self
249
    {
250
        if ($this->compiled) {
1✔
251
            return $this;
1✔
252
        }
253

254
        if ($this->data['ext'] != 'scss') {
1✔
255
            return $this;
1✔
256
        }
257

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

320
        return $this;
1✔
321
    }
322

323
    /**
324
     * Minifying a CSS or a JS.
325
     *
326
     * @throws RuntimeException
327
     */
328
    public function minify(): self
329
    {
330
        // disable minify to preserve inline source map
331
        if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) {
1✔
UNCOV
332
            return $this;
×
333
        }
334

335
        if ($this->minified) {
1✔
UNCOV
336
            return $this;
×
337
        }
338

339
        if ($this->data['ext'] == 'scss') {
1✔
UNCOV
340
            $this->compile();
×
341
        }
342

343
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
1✔
UNCOV
344
            return $this;
×
345
        }
346

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

350
            return $this;
×
351
        }
352

353
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
354
        $cacheKey = $cache->createKeyFromAsset($this, ['minified']);
1✔
355
        if (!$cache->has($cacheKey)) {
1✔
356
            switch ($this->data['ext']) {
1✔
357
                case 'css':
1✔
358
                    $minifier = new Minify\CSS($this->data['content']);
1✔
359
                    break;
1✔
360
                case 'js':
1✔
361
                    $minifier = new Minify\JS($this->data['content']);
1✔
362
                    break;
1✔
363
                default:
364
                    throw new RuntimeException(sprintf('Not able to minify "%s".', $this->data['path']));
×
365
            }
366
            $this->data['path'] = preg_replace(
1✔
367
                '/\.' . $this->data['ext'] . '$/m',
1✔
368
                '.min.' . $this->data['ext'],
1✔
369
                $this->data['path']
1✔
370
            );
1✔
371
            $this->data['content'] = $minifier->minify();
1✔
372
            $this->data['size'] = \strlen($this->data['content']);
1✔
373
            $this->minified = true;
1✔
374
            $cache->set($cacheKey, $this->data);
1✔
375
        }
376
        $this->data = $cache->get($cacheKey);
1✔
377

378
        return $this;
1✔
379
    }
380

381
    /**
382
     * Optimizing an image.
383
     */
384
    public function optimize(string $filepath): self
385
    {
386
        if ($this->data['type'] != 'image') {
1✔
387
            return $this;
1✔
388
        }
389

390
        $quality = $this->config->get('assets.images.quality') ?? 75;
1✔
391
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
392
        $tags = ["q$quality", 'optimized'];
1✔
393
        if ($this->data['width']) {
1✔
394
            array_unshift($tags, "{$this->data['width']}x");
1✔
395
        }
396
        $cacheKey = $cache->createKeyFromAsset($this, $tags);
1✔
397
        if (!$cache->has($cacheKey)) {
1✔
398
            $message = $filepath;
1✔
399
            $sizeBefore = filesize($filepath);
1✔
400
            Optimizer::create($quality)->optimize($filepath);
1✔
401
            $sizeAfter = filesize($filepath);
1✔
402
            if ($sizeAfter < $sizeBefore) {
1✔
UNCOV
403
                $message = sprintf(
×
UNCOV
404
                    '%s (%s Ko -> %s Ko)',
×
UNCOV
405
                    $message,
×
UNCOV
406
                    ceil($sizeBefore / 1000),
×
UNCOV
407
                    ceil($sizeAfter / 1000)
×
UNCOV
408
                );
×
409
            }
410
            $this->data['content'] = Util\File::fileGetContents($filepath);
1✔
411
            $this->data['size'] = $sizeAfter;
1✔
412
            $cache->set($cacheKey, $this->data);
1✔
413
            $this->builder->getLogger()->debug(sprintf('Asset "%s" optimized', $message));
1✔
414
        }
415
        $this->data = $cache->get($cacheKey, $this->data);
1✔
416

417
        return $this;
1✔
418
    }
419

420
    /**
421
     * Resizes an image with a new $width.
422
     *
423
     * @throws RuntimeException
424
     */
425
    public function resize(int $width): self
426
    {
427
        if ($this->data['missing']) {
1✔
UNCOV
428
            throw new RuntimeException(sprintf('Not able to resize "%s": file not found.', $this->data['path']));
×
429
        }
430
        if ($this->data['type'] != 'image') {
1✔
UNCOV
431
            throw new RuntimeException(sprintf('Not able to resize "%s": not an image.', $this->data['path']));
×
432
        }
433
        if ($width >= $this->data['width']) {
1✔
434
            return $this;
1✔
435
        }
436

437
        $assetResized = clone $this;
1✔
438
        $assetResized->data['width'] = $width;
1✔
439

440
        if ($this->isImageInCdn()) {
1✔
UNCOV
441
            return $assetResized; // returns the asset with the new width only: CDN do the rest of the job
×
442
        }
443

444
        $quality = $this->config->get('assets.images.quality');
1✔
445
        $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir'));
1✔
446
        $cacheKey = $cache->createKeyFromAsset($assetResized, ["{$width}x", "q$quality"]);
1✔
447
        if (!$cache->has($cacheKey)) {
1✔
448
            if ($assetResized->data['type'] !== 'image') {
1✔
UNCOV
449
                throw new RuntimeException(sprintf('Not able to resize "%s".', $assetResized->data['path']));
×
450
            }
451
            if (!\extension_loaded('gd')) {
1✔
UNCOV
452
                throw new RuntimeException('GD extension is required to use images resize.');
×
453
            }
454

455
            try {
456
                $img = ImageManager::make($assetResized->data['content_source'])->encode($assetResized->data['ext']);
1✔
457
                $img->resize($width, null, function (\Intervention\Image\Constraint $constraint) {
1✔
458
                    $constraint->aspectRatio();
1✔
459
                    $constraint->upsize();
1✔
460
                });
1✔
UNCOV
461
            } catch (\Exception $e) {
×
UNCOV
462
                throw new RuntimeException(sprintf('Not able to resize image "%s": %s', $assetResized->data['path'], $e->getMessage()));
×
463
            }
464
            $assetResized->data['path'] = '/' . Util::joinPath(
1✔
465
                (string) $this->config->get('assets.target'),
1✔
466
                (string) $this->config->get('assets.images.resize.dir'),
1✔
467
                (string) $width,
1✔
468
                $assetResized->data['path']
1✔
469
            );
1✔
470

471
            try {
472
                if ($assetResized->data['subtype'] == 'image/jpeg') {
1✔
UNCOV
473
                    $img->interlace();
×
474
                }
475
                $assetResized->data['content'] = (string) $img->encode($assetResized->data['ext'], $quality);
1✔
476
                $img->destroy();
1✔
477
                $assetResized->data['height'] = $assetResized->getHeight();
1✔
478
                $assetResized->data['size'] = \strlen($assetResized->data['content']);
1✔
UNCOV
479
            } catch (\Exception $e) {
×
UNCOV
480
                throw new RuntimeException(sprintf('Not able to encode image "%s": %s', $assetResized->data['path'], $e->getMessage()));
×
481
            }
482

483
            $cache->set($cacheKey, $assetResized->data);
1✔
484
        }
485
        $assetResized->data = $cache->get($cacheKey);
1✔
486

487
        return $assetResized;
1✔
488
    }
489

490
    /**
491
     * Converts an image asset to WebP format.
492
     *
493
     * @throws RuntimeException
494
     */
495
    public function webp(?int $quality = null): self
496
    {
497
        if ($this->data['type'] !== 'image') {
1✔
UNCOV
498
            throw new RuntimeException(sprintf('can\'t convert "%s" (%s) to WebP: it\'s not an image file.', $this->data['path'], $this->data['type']));
×
499
        }
500

501
        if ($quality === null) {
1✔
502
            $quality = (int) $this->config->get('assets.images.quality') ?? 75;
1✔
503
        }
504

505
        $assetWebp = clone $this;
1✔
506
        $format = 'webp';
1✔
507
        $assetWebp['ext'] = $format;
1✔
508

509
        if ($this->isImageInCdn()) {
1✔
UNCOV
510
            return $assetWebp; // returns the asset with the new extension ('webp') only: CDN do the rest of the job
×
511
        }
512

513
        $img = ImageManager::make($assetWebp['content']);
1✔
514
        $assetWebp['content'] = (string) $img->encode($format, $quality);
1✔
515
        $img->destroy();
1✔
516
        $assetWebp['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']);
1✔
517
        $assetWebp['subtype'] = "image/$format";
1✔
518
        $assetWebp['size'] = \strlen($assetWebp['content']);
1✔
519

520
        return $assetWebp;
1✔
521
    }
522

523
    /**
524
     * Implements \ArrayAccess.
525
     */
526
    #[\ReturnTypeWillChange]
527
    public function offsetSet($offset, $value): void
528
    {
529
        if (!\is_null($offset)) {
1✔
530
            $this->data[$offset] = $value;
1✔
531
        }
532
    }
533

534
    /**
535
     * Implements \ArrayAccess.
536
     */
537
    #[\ReturnTypeWillChange]
538
    public function offsetExists($offset): bool
539
    {
540
        return isset($this->data[$offset]);
1✔
541
    }
542

543
    /**
544
     * Implements \ArrayAccess.
545
     */
546
    #[\ReturnTypeWillChange]
547
    public function offsetUnset($offset): void
548
    {
UNCOV
549
        unset($this->data[$offset]);
×
550
    }
551

552
    /**
553
     * Implements \ArrayAccess.
554
     */
555
    #[\ReturnTypeWillChange]
556
    public function offsetGet($offset)
557
    {
558
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
1✔
559
    }
560

561
    /**
562
     * Hashing content of an asset with the specified algo, sha384 by default.
563
     * Used for SRI (Subresource Integrity).
564
     *
565
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
566
     */
567
    public function getIntegrity(string $algo = 'sha384'): string
568
    {
569
        return sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
1✔
570
    }
571

572
    /**
573
     * Returns MP3 file infos.
574
     *
575
     * @see https://github.com/wapmorgan/Mp3Info
576
     */
577
    public function getAudio(): Mp3Info
578
    {
579
        if ($this->data['type'] !== 'audio') {
1✔
UNCOV
580
            throw new RuntimeException(sprintf('Not able to get audio infos of "%s".', $this->data['path']));
×
581
        }
582

583
        return new Mp3Info($this->data['file']);
1✔
584
    }
585

586
    /**
587
     * Returns MP4 file infos.
588
     *
589
     * @see https://github.com/clwu88/php-read-mp4info
590
     */
591
    public function getVideo(): array
592
    {
UNCOV
593
        if ($this->data['type'] !== 'video') {
×
594
            throw new RuntimeException(sprintf('Not able to get video infos of "%s".', $this->data['path']));
×
595
        }
596

UNCOV
597
        return \Clwu\Mp4::getInfo($this->data['file']);
×
598
    }
599

600
    /**
601
     * Returns the data URL (encoded in Base64).
602
     *
603
     * @throws RuntimeException
604
     */
605
    public function dataurl(): string
606
    {
607
        if ($this->data['type'] == 'image' && !$this->isSVG()) {
1✔
608
            return (string) ImageManager::make($this->data['content'])->encode('data-url', $this->config->get('assets.images.quality'));
1✔
609
        }
610

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

614
    /**
615
     * Saves file.
616
     * Note: a file from `static/` with the same name will NOT be overridden.
617
     *
618
     * @throws RuntimeException
619
     */
620
    public function save(): void
621
    {
622
        $filepath = Util::joinFile($this->config->getOutputPath(), $this->data['path']);
1✔
623
        if (!$this->builder->getBuildOptions()['dry-run'] && !Util\File::getFS()->exists($filepath)) {
1✔
624
            try {
625
                Util\File::getFS()->dumpFile($filepath, $this->data['content']);
1✔
626
                $this->builder->getLogger()->debug(sprintf('Asset "%s" saved', $filepath));
1✔
627
                if ($this->optimize) {
1✔
628
                    $this->optimize($filepath);
1✔
629
                }
NEW
630
            } catch (\Symfony\Component\Filesystem\Exception\IOException) {
×
UNCOV
631
                if (!$this->ignore_missing) {
×
UNCOV
632
                    throw new RuntimeException(sprintf('Can\'t save asset "%s".', $filepath));
×
633
                }
634
            }
635
        }
636
    }
637

638
    /**
639
     * Is Asset is an image in CDN.
640
     *
641
     * @return bool
642
     */
643
    public function isImageInCdn()
644
    {
645
        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✔
646
            return false;
1✔
647
        }
648
        // remote image?
UNCOV
649
        if ($this->data['url'] !== null && (bool) $this->config->get('assets.images.cdn.remote') !== true) {
×
UNCOV
650
            return false;
×
651
        }
652

UNCOV
653
        return true;
×
654
    }
655

656
    /**
657
     * Load file data.
658
     *
659
     * @throws RuntimeException
660
     */
661
    private function loadFile(string $path, bool $ignore_missing = false, ?string $remote_fallback = null, bool $force_slash = true): array
662
    {
663
        $file = [
1✔
664
            'url' => null,
1✔
665
        ];
1✔
666

667
        try {
668
            $filePath = $this->findFile($path, $remote_fallback);
1✔
669
        } catch (RuntimeException $e) {
1✔
670
            if ($ignore_missing) {
1✔
671
                $file['path'] = $path;
1✔
672
                $file['missing'] = true;
1✔
673

674
                return $file;
1✔
675
            }
676

UNCOV
677
            throw new RuntimeException(sprintf('Can\'t load asset file "%s" (%s).', $path, $e->getMessage()));
×
678
        }
679

680
        if (Util\Url::isUrl($path)) {
1✔
681
            $file['url'] = $path;
1✔
682
            $path = Util::joinPath(
1✔
683
                (string) $this->config->get('assets.target'),
1✔
684
                Util\File::getFS()->makePathRelative($filePath, $this->config->getCacheAssetsRemotePath())
1✔
685
            );
1✔
686
            // remote_fallback in assets/ ont in cache/assets/remote/
687
            if (substr(Util\File::getFS()->makePathRelative($filePath, $this->config->getCacheAssetsRemotePath()), 0, 2) == '..') {
1✔
UNCOV
688
                $path = Util::joinPath(
×
UNCOV
689
                    (string) $this->config->get('assets.target'),
×
UNCOV
690
                    Util\File::getFS()->makePathRelative($filePath, $this->config->getAssetsPath())
×
691
                );
×
692
            }
693
            $force_slash = true;
1✔
694
        }
695
        if ($force_slash) {
1✔
696
            $path = '/' . ltrim($path, '/');
1✔
697
        }
698

699
        list($type, $subtype) = Util\File::getMimeType($filePath);
1✔
700
        $content = Util\File::fileGetContents($filePath);
1✔
701

702
        $file['filepath'] = $filePath;
1✔
703
        $file['path'] = $path;
1✔
704
        $file['ext'] = pathinfo($path)['extension'] ?? '';
1✔
705
        $file['type'] = $type;
1✔
706
        $file['subtype'] = $subtype;
1✔
707
        $file['size'] = filesize($filePath);
1✔
708
        $file['content'] = $content;
1✔
709
        $file['missing'] = false;
1✔
710

711
        return $file;
1✔
712
    }
713

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

UNCOV
766
                    throw new RuntimeException($e->getMessage());
×
767
                }
768
                if (false === $content = Util\File::fileGetContents($url, true)) {
1✔
UNCOV
769
                    throw new RuntimeException(sprintf('Can\'t get content of "%s"', $url));
×
770
                }
771
                if (\strlen($content) <= 1) {
1✔
772
                    throw new RuntimeException(sprintf('Asset at "%s" is empty', $url));
×
773
                }
774
                // put file in cache
775
                Util\File::getFS()->dumpFile($filePath, $content);
1✔
776
            }
777

778
            return $filePath;
1✔
779
        }
780

781
        // checks in assets/
782
        $filePath = Util::joinFile($this->config->getAssetsPath(), $path);
1✔
783
        if (Util\File::getFS()->exists($filePath)) {
1✔
784
            return $filePath;
1✔
785
        }
786

787
        // checks in each themes/<theme>/assets/
788
        foreach ($this->config->getTheme() as $theme) {
1✔
789
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path);
1✔
790
            if (Util\File::getFS()->exists($filePath)) {
1✔
791
                return $filePath;
1✔
792
            }
793
        }
794

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

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

809
        throw new RuntimeException(sprintf('Can\'t find file "%s".', $path));
1✔
810
    }
811

812
    /**
813
     * Returns the width of an image/SVG.
814
     *
815
     * @throws RuntimeException
816
     */
817
    private function getWidth(): int
818
    {
819
        if ($this->data['type'] != 'image') {
1✔
UNCOV
820
            return 0;
×
821
        }
822
        if ($this->isSVG() && false !== $svg = $this->getSvgAttributes()) {
1✔
823
            return (int) $svg->width;
1✔
824
        }
825
        if (false === $size = $this->getImageSize()) {
1✔
UNCOV
826
            throw new RuntimeException(sprintf('Not able to get width of "%s".', $this->data['path']));
×
827
        }
828

829
        return $size[0];
1✔
830
    }
831

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

849
        return $size[1];
1✔
850
    }
851

852
    /**
853
     * Returns image size informations.
854
     *
855
     * @see https://www.php.net/manual/function.getimagesize.php
856
     *
857
     * @return array|false
858
     */
859
    private function getImageSize()
860
    {
861
        if (!$this->data['type'] == 'image') {
1✔
UNCOV
862
            return false;
×
863
        }
864

865
        try {
866
            if (false === $size = getimagesizefromstring($this->data['content'])) {
1✔
867
                return false;
1✔
868
            }
UNCOV
869
        } catch (\Exception $e) {
×
UNCOV
870
            throw new RuntimeException(sprintf('Handling asset "%s" failed: "%s"', $this->data['path_source'], $e->getMessage()));
×
871
        }
872

873
        return $size;
1✔
874
    }
875

876
    /**
877
     * Returns true if asset is a SVG.
878
     */
879
    private function isSVG(): bool
880
    {
881
        return \in_array($this->data['subtype'], ['image/svg', 'image/svg+xml']) || $this->data['ext'] == 'svg';
1✔
882
    }
883

884
    /**
885
     * Returns SVG attributes.
886
     *
887
     * @return \SimpleXMLElement|false
888
     */
889
    private function getSvgAttributes()
890
    {
891
        if (false === $xml = simplexml_load_string($this->data['content_source'])) {
1✔
UNCOV
892
            return false;
×
893
        }
894

895
        return $xml->attributes();
1✔
896
    }
897

898
    /**
899
     * Replaces some characters by '_'.
900
     */
901
    private function sanitize(string $string): string
902
    {
903
        return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string);
1✔
904
    }
905

906
    /**
907
     * Builds CDN image URL.
908
     */
909
    private function buildImageCdnUrl(): string
910
    {
UNCOV
911
        return str_replace(
×
UNCOV
912
            [
×
UNCOV
913
                '%account%',
×
UNCOV
914
                '%image_url%',
×
UNCOV
915
                '%width%',
×
UNCOV
916
                '%quality%',
×
UNCOV
917
                '%format%',
×
UNCOV
918
            ],
×
UNCOV
919
            [
×
UNCOV
920
                $this->config->get('assets.images.cdn.account'),
×
UNCOV
921
                ltrim($this->data['url'] ?? (string) new Url($this->builder, $this->data['path'], ['canonical' => $this->config->get('assets.images.cdn.canonical') ?? true]), '/'),
×
UNCOV
922
                $this->data['width'],
×
UNCOV
923
                $this->config->get('assets.images.quality') ?? 75,
×
UNCOV
924
                $this->data['ext'],
×
925
            ],
×
926
            (string) $this->config->get('assets.images.cdn.url')
×
927
        );
×
928
    }
929
}
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