Passed
Push — asset-image ( 267340 )
by Arnaud
05:29
created

Asset::save()   B

Complexity

Conditions 8
Paths 24

Size

Total Lines 24
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
eloc 19
c 2
b 0
f 0
nc 24
nop 0
dl 0
loc 24
rs 8.4444
1
<?php
2
/**
3
 * This file is part of the Cecil/Cecil package.
4
 *
5
 * Copyright (c) Arnaud Ligny <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cecil\Assets;
12
13
use Cecil\Builder;
14
use Cecil\Collection\Page\Page;
15
use Cecil\Config;
16
use Cecil\Exception\Exception;
17
use Cecil\Util;
18
use Intervention\Image\ImageManagerStatic as ImageManager;
19
use MatthiasMullie\Minify;
20
use ScssPhp\ScssPhp\Compiler;
21
use Spatie\ImageOptimizer\OptimizerChainFactory as Optimizer;
22
use wapmorgan\Mp3Info\Mp3Info;
23
24
class Asset implements \ArrayAccess
25
{
26
    /** @var Builder */
27
    protected $builder;
28
29
    /** @var Config */
30
    protected $config;
31
32
    /** @var array */
33
    protected $data = [];
34
35
    /** @var bool */
36
    protected $fingerprinted = false;
37
38
    /** @var bool */
39
    protected $compiled = false;
40
41
    /** @var bool */
42
    protected $minified = false;
43
44
    /** @var bool */
45
    protected $ignore_missing = false;
46
47
    /**
48
     * Creates an Asset from file(s) path.
49
     *
50
     * $options[
51
     *     'fingerprint'    => true,
52
     *     'minify'         => true,
53
     *     'filename'       => '',
54
     *     'ignore_missing' => false,
55
     * ];
56
     *
57
     * @param Builder      $builder
58
     * @param string|array $paths
59
     * @param array|null   $options
60
     */
61
    public function __construct(Builder $builder, $paths, array $options = null)
62
    {
63
        $this->builder = $builder;
64
        $this->config = $builder->getConfig();
65
        $paths = is_array($paths) ? $paths : [$paths];
66
        array_walk($paths, function ($path) {
67
            if (empty($path)) {
68
                throw new Exception('The path parameter of "asset() can\'t be empty."');
69
            }
70
        });
71
        $this->data = [
72
            'file'           => '',
73
            'filename'       => '',
74
            'path_source'    => '',
75
            'path'           => '',
76
            'ext'            => '',
77
            'type'           => '',
78
            'subtype'        => '',
79
            'size'           => 0,
80
            'content_source' => '',
81
            'content'        => '',
82
        ];
83
84
        // handles options
85
        $fingerprint = (bool) $this->config->get('assets.fingerprint.enabled');
86
        $minify = (bool) $this->config->get('assets.minify.enabled');
87
        $filename = '';
88
        $ignore_missing = false;
89
        extract(is_array($options) ? $options : [], EXTR_IF_EXISTS);
90
        $this->ignore_missing = $ignore_missing;
91
92
        // fill data array with file(s) informations
93
        $cache = new Cache($this->builder, 'assets');
94
        $cacheKey = sprintf('%s.ser', implode('_', $paths));
95
        if (!$cache->has($cacheKey)) {
96
            $pathsCount = count($paths);
97
            $file = [];
98
            for ($i = 0; $i < $pathsCount; $i++) {
99
                // loads file(s)
100
                $file[$i] = $this->loadFile($paths[$i], $ignore_missing);
101
                // bundle: same type/ext only
102
                if ($i > 0) {
103
                    if ($file[$i]['type'] != $file[$i - 1]['type']) {
104
                        throw new Exception(\sprintf('Asset bundle type error (%s != %s).', $file[$i]['type'], $file[$i - 1]['type']));
105
                    }
106
                    if ($file[$i]['ext'] != $file[$i - 1]['ext']) {
107
                        throw new Exception(\sprintf('Asset bundle extension error (%s != %s).', $file[$i]['ext'], $file[$i - 1]['ext']));
108
                    }
109
                }
110
                // missing allowed = empty path
111
                if ($file[$i]['missing']) {
112
                    $this->data['path'] = '';
113
114
                    continue;
115
                }
116
                // set data
117
                if ($i == 0) {
118
                    $this->data['file'] = $file[$i]['filepath']; // should be an array of files in case of bundle?
119
                    $this->data['filename'] = $file[$i]['path'];
120
                    $this->data['path_source'] = $file[$i]['path'];
121
                    $this->data['path'] = $file[$i]['path'];
122
                    if (!empty($filename)) {
123
                        $this->data['path'] = '/'.ltrim($filename, '/');
124
                    }
125
                    $this->data['ext'] = $file[$i]['ext'];
126
                    $this->data['type'] = $file[$i]['type'];
127
                    $this->data['subtype'] = $file[$i]['subtype'];
128
                }
129
                $this->data['size'] += $file[$i]['size'];
130
                $this->data['content_source'] .= $file[$i]['content'];
131
                $this->data['content'] .= $file[$i]['content'];
132
            }
133
            // bundle: define path
134
            if ($pathsCount > 1) {
135
                if (empty($filename)) {
136
                    switch ($this->data['ext']) {
137
                        case 'scss':
138
                        case 'css':
139
                            $this->data['path'] = '/styles.'.$file[0]['ext'];
140
                            break;
141
                        case 'js':
142
                            $this->data['path'] = '/scripts.'.$file[0]['ext'];
143
                            break;
144
                        default:
145
                            throw new Exception(\sprintf('Asset bundle supports "%s" files only.', 'scss, css and js'));
146
                    }
147
                }
148
            }
149
            $cache->set($cacheKey, $this->data);
150
        }
151
        $this->data = $cache->get($cacheKey);
152
153
        // fingerprinting
154
        if ($fingerprint) {
155
            $this->fingerprint();
156
        }
157
        // compiling
158
        if ((bool) $this->config->get('assets.compile.enabled')) {
159
            $this->compile();
160
        }
161
        // minifying
162
        if ($minify) {
163
            $this->minify();
164
        }
165
    }
166
167
    /**
168
     * Returns path.
169
     */
170
    public function __toString(): string
171
    {
172
        try {
173
            $this->save();
174
        } catch (Exception $e) {
175
            $this->builder->getLogger()->error($e->getMessage());
176
        }
177
178
        return $this->data['path'];
179
    }
180
181
    /**
182
     * Fingerprints a file.
183
     */
184
    public function fingerprint(): self
185
    {
186
        if ($this->fingerprinted) {
187
            return $this;
188
        }
189
190
        $fingerprint = hash('md5', $this->data['content_source']);
191
        $this->data['path'] = preg_replace(
192
            '/\.'.$this->data['ext'].'$/m',
193
            ".$fingerprint.".$this->data['ext'],
194
            $this->data['path']
195
        );
196
197
        $this->fingerprinted = true;
198
199
        return $this;
200
    }
201
202
    /**
203
     * Compiles a SCSS.
204
     */
205
    public function compile(): self
206
    {
207
        if ($this->compiled) {
208
            return $this;
209
        }
210
211
        if ($this->data['ext'] != 'scss') {
212
            return $this;
213
        }
214
215
        $cache = new Cache($this->builder, 'assets');
216
        $cacheKey = $cache->createKeyFromAsset($this, 'compiled');
217
        if (!$cache->has($cacheKey)) {
218
            $scssPhp = new Compiler();
219
            // import path
220
            $scssPhp->addImportPath(Util::joinPath($this->config->getStaticPath()));
221
            $scssDir = $this->config->get('assets.compile.import') ?? [];
222
            $themes = $this->config->getTheme() ?? [];
223
            foreach ($scssDir as $dir) {
224
                $scssPhp->addImportPath(Util::joinPath($this->config->getStaticPath(), $dir));
225
                $scssPhp->addImportPath(Util::joinPath(dirname($this->data['file']), $dir));
226
                foreach ($themes as $theme) {
227
                    $scssPhp->addImportPath(Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir")));
228
                }
229
            }
230
            // source map
231
            if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) {
232
                $importDir = [];
233
                $staticDir = (string) $this->config->get('static.dir');
234
                $staticDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR.$staticDir.DIRECTORY_SEPARATOR);
235
                $fileRelPath = substr($this->data['file'], $staticDirPos + 8);
236
                $filePath = Util::joinFile($this->config->getOutputPath(), $this->config->get('static.target') ?? '', $fileRelPath);
237
                $importDir[] = dirname($filePath);
238
                foreach ($scssDir as $dir) {
239
                    $importDir[] = Util::joinFile($this->config->getOutputPath(), $this->config->get('static.target') ?? '', $dir);
240
                }
241
                $scssPhp->setImportPaths(array_unique($importDir));
242
                $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE);
243
                $scssPhp->setSourceMapOptions([
244
                    'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()),
245
                    'sourceRoot'        => '/',
246
                ]);
247
            }
248
            // output style
249
            $outputStyles = ['expanded', 'compressed'];
250
            $outputStyle = strtolower((string) $this->config->get('assets.compile.style'));
251
            if (!in_array($outputStyle, $outputStyles)) {
252
                throw new Exception(\sprintf('Scss output style "%s" doesn\'t exists.', $outputStyle));
253
            }
254
            $scssPhp->setOutputStyle($outputStyle);
255
            // variables
256
            $variables = $this->config->get('assets.compile.variables') ?? [];
257
            if (!empty($variables)) {
258
                $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables);
259
                $scssPhp->replaceVariables($variables);
260
            }
261
            // update data
262
            $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']);
263
            $this->data['ext'] = 'css';
264
            $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss();
265
            $this->compiled = true;
266
            $cache->set($cacheKey, $this->data);
267
        }
268
        $this->data = $cache->get($cacheKey);
269
270
        return $this;
271
    }
272
273
    /**
274
     * Minifying a CSS or a JS.
275
     */
276
    public function minify(): self
277
    {
278
        // disable minify for sourcemap
279
        if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) {
280
            return $this;
281
        }
282
283
        if ($this->minified) {
284
            return $this;
285
        }
286
287
        if ($this->data['ext'] == 'scss') {
288
            $this->compile();
289
        }
290
291
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
292
            return $this;
293
        }
294
295
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
296
            $this->minified;
297
298
            return $this;
299
        }
300
301
        $cache = new Cache($this->builder, 'assets');
302
        $cacheKey = $cache->createKeyFromAsset($this, 'minified');
303
        if (!$cache->has($cacheKey)) {
304
            switch ($this->data['ext']) {
305
                case 'css':
306
                    $minifier = new Minify\CSS($this->data['content']);
307
                    break;
308
                case 'js':
309
                    $minifier = new Minify\JS($this->data['content']);
310
                    break;
311
                default:
312
                    throw new Exception(sprintf('Not able to minify "%s"', $this->data['path']));
313
            }
314
            $this->data['path'] = preg_replace(
315
                '/\.'.$this->data['ext'].'$/m',
316
                '.min.'.$this->data['ext'],
317
                $this->data['path']
318
            );
319
            $this->data['content'] = $minifier->minify();
320
            $this->minified = true;
321
            $cache->set($cacheKey, $this->data);
322
        }
323
        $this->data = $cache->get($cacheKey);
324
325
        return $this;
326
    }
327
328
    /**
329
     * Resizes an image.
330
     */
331
    public function resize(int $size): self
332
    {
333
        $cache = new Cache($this->builder, 'assets');
334
        $cacheKey = $cache->createKeyFromAsset($this, $size);
335
        if (!$cache->has($cacheKey)) {
336
            if ($this->data['type'] !== 'image') {
337
                throw new Exception(sprintf('Not able to resize "%s"', $this->data['path']));
338
            }
339
            if (!extension_loaded('gd')) {
340
                throw new Exception('GD extension is required to use images resize.');
341
            }
342
343
            try {
344
                $img = ImageManager::make($this->data['content_source']);
345
                $img->resize($size, null, function (\Intervention\Image\Constraint $constraint) {
346
                    $constraint->aspectRatio();
347
                    $constraint->upsize();
348
                });
349
            } catch (\Exception $e) {
350
                throw new Exception(sprintf('Not able to resize image "%s": %s', $this->data['path'], $e->getMessage()));
351
            }
352
            $this->data['path'] = '/'.Util::joinPath((string) $this->config->get('assets.target'), 'thumbnails', (string) $size, $this->data['path_source']);
353
354
            try {
355
                $this->data['content'] = (string) $img->encode($this->data['ext'], $this->config->get('assets.images.quality'));
356
            } catch (\Exception $e) {
357
                throw new Exception(sprintf('Not able to encode image "%s": %s', $this->data['path'], $e->getMessage()));
358
            }
359
360
            $cache->set($cacheKey, $this->data);
361
        }
362
        $this->data = $cache->get($cacheKey);
363
364
        return $this;
365
    }
366
367
    /**
368
     * Returns the data URL of an image.
369
     */
370
    public function dataurl(): string
371
    {
372
        if ($this->data['type'] !== 'image') {
373
            throw new Exception(sprintf('Can\'t get data URL of "%s"', $this->data['path']));
374
        }
375
376
        return (string) ImageManager::make($this->data['content'])->encode('data-url', $this->config->get('assets.images.quality'));
377
    }
378
379
    /**
380
     * Implements \ArrayAccess.
381
     */
382
    public function offsetSet($offset, $value)
383
    {
384
        if (!is_null($offset)) {
385
            $this->data[$offset] = $value;
386
        }
387
    }
388
389
    /**
390
     * Implements \ArrayAccess.
391
     */
392
    public function offsetExists($offset)
393
    {
394
        return isset($this->data[$offset]);
395
    }
396
397
    /**
398
     * Implements \ArrayAccess.
399
     */
400
    public function offsetUnset($offset)
401
    {
402
        unset($this->data[$offset]);
403
    }
404
405
    /**
406
     * Implements \ArrayAccess.
407
     */
408
    public function offsetGet($offset)
409
    {
410
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
411
    }
412
413
    /**
414
     * Hashing content of an asset with the specified algo, sha384 by default.
415
     * Used for SRI (Subresource Integrity).
416
     *
417
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
418
     */
419
    public function getIntegrity(string $algo = 'sha384'): string
420
    {
421
        return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
422
    }
423
424
    /**
425
     * Returns the width of an image.
426
     *
427
     * @return false|int
428
     */
429
    public function getWidth()
430
    {
431
        if (false === $size = $this->getImageSize()) {
432
            return false;
433
        }
434
435
        return $size[0];
436
    }
437
438
    /**
439
     * Returns the height of an image.
440
     *
441
     * @return false|int
442
     */
443
    public function getHeight()
444
    {
445
        if (false === $size = $this->getImageSize()) {
446
            return false;
447
        }
448
449
        return $size[1];
450
    }
451
452
    /**
453
     * Returns MP3 file infos.
454
     *
455
     * @see https://github.com/wapmorgan/Mp3Info
456
     */
457
    public function getAudio(): Mp3Info
458
    {
459
        return new Mp3Info($this->data['file']);
460
    }
461
462
    /**
463
     * Saves file.
464
     * Note: a file from `static/` with the same name will NOT be overridden.
465
     *
466
     * @throws Exception
467
     */
468
    public function save(): void
469
    {
470
        $filepath = Util::joinFile($this->config->getOutputPath(), $this->data['path']);
471
        if (!$this->builder->getBuildOptions()['dry-run'] && !Util\File::getFS()->exists($filepath)) {
472
            try {
473
                $message = \sprintf('Save asset "%s"', $this->data['path']);
474
                Util\File::getFS()->dumpFile($filepath, $this->data['content']);
475
                if ($this->data['type'] == 'image' && $this->config->get('assets.images.optimize')) {
476
                    $sizeBefore = filesize($filepath);
477
                    Optimizer::create()->optimize($filepath);
478
                    $sizeAfter = filesize($filepath);
479
                    if ($sizeAfter < $sizeBefore) {
480
                        $message = \sprintf(
481
                            '%s (%s Ko -> %s Ko)',
482
                            $message,
483
                            ceil($sizeBefore / 1000),
484
                            ceil($sizeAfter / 1000)
485
                        );
486
                    }
487
                }
488
                $this->builder->getLogger()->debug($message);
489
            } catch (\Symfony\Component\Filesystem\Exception\IOException $e) {
490
                if (!$this->ignore_missing) {
491
                    throw new Exception(\sprintf('Can\'t save asset "%s"', $this->data['path']));
492
                }
493
            }
494
        }
495
    }
496
497
    /**
498
     * Load file data.
499
     */
500
    private function loadFile(string $path, bool $ignore_missing = false): array
501
    {
502
        $file = [];
503
504
        if (false === $filePath = $this->findFile($path)) {
505
            if ($ignore_missing) {
506
                $file['missing'] = true;
507
508
                return $file;
509
            }
510
511
            throw new Exception(sprintf('Asset file "%s" doesn\'t exist.', $path));
512
        }
513
514
        if (Util\Url::isUrl($path)) {
515
            $urlHost = parse_url($path, PHP_URL_HOST);
516
            $urlPath = parse_url($path, PHP_URL_PATH);
517
            $urlQuery = parse_url($path, PHP_URL_QUERY);
518
            $path = Util::joinPath((string) $this->config->get('assets.target'), $urlHost, $urlPath);
519
            if (!empty($urlQuery)) {
520
                $path = Util::joinPath($path, Page::slugify($urlQuery));
521
                // Google Fonts hack
522
                if (strpos($urlPath, '/css') !== false) {
523
                    $path .= '.css';
524
                }
525
            }
526
        }
527
        $path = '/'.ltrim($path, '/');
528
529
        $pathinfo = pathinfo($path);
530
        list($type, $subtype) = Util\File::getMimeType($filePath);
531
        $content = Util\File::fileGetContents($filePath);
532
533
        $file['filepath'] = $filePath;
534
        $file['path'] = $path;
535
        $file['ext'] = $pathinfo['extension'];
536
        $file['type'] = $type;
537
        $file['subtype'] = $subtype;
538
        $file['size'] = filesize($filePath);
539
        $file['content'] = $content;
540
        $file['missing'] = false;
541
542
        return $file;
543
    }
544
545
    /**
546
     * Try to find the file:
547
     *   1. remote (if $path is a valid URL)
548
     *   2. in static/
549
     *   3. in themes/<theme>/static/
550
     * Returns local file path or false if file don't exists.
551
     *
552
     * @return string|false
553
     */
554
    private function findFile(string $path)
555
    {
556
        // in case of remote file: save it and returns cached file path
557
        if (Util\Url::isUrl($path)) {
558
            $url = $path;
559
            $relativePath = Page::slugify(sprintf('%s%s-%s', parse_url($url, PHP_URL_HOST), parse_url($url, PHP_URL_PATH), parse_url($url, PHP_URL_QUERY)));
560
            $filePath = Util::joinFile($this->config->getCacheAssetsPath(), $relativePath);
561
            if (!file_exists($filePath)) {
562
                if (!Util\Url::isRemoteFileExists($url)) {
563
                    return false;
564
                }
565
                if (false === $content = Util\File::fileGetContents($url, true)) {
566
                    return false;
567
                }
568
                if (strlen($content) <= 1) {
569
                    throw new Exception(sprintf('Asset at "%s" is empty.', $url));
570
                }
571
                Util\File::getFS()->dumpFile($filePath, $content);
572
            }
573
574
            return $filePath;
575
        }
576
577
        // checks in static/
578
        $filePath = Util::joinFile($this->config->getStaticPath(), $path);
579
        if (Util\File::getFS()->exists($filePath)) {
580
            return $filePath;
581
        }
582
583
        // checks in each themes/<theme>/static/
584
        foreach ($this->config->getTheme() as $theme) {
585
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
586
            if (Util\File::getFS()->exists($filePath)) {
587
                return $filePath;
588
            }
589
        }
590
591
        return false;
592
    }
593
594
    /**
595
     * Returns image size informations.
596
     *
597
     * @see https://www.php.net/manual/function.getimagesize.php
598
     *
599
     * @return false|array
600
     */
601
    private function getImageSize()
602
    {
603
        if (!$this->data['type'] == 'image') {
604
            return false;
605
        }
606
607
        if (false === $size = getimagesizefromstring($this->data['content'])) {
608
            return false;
609
        }
610
611
        return $size;
612
    }
613
}
614