Passed
Push — asset-image ( a2efff...e5f01a )
by Arnaud
03:15
created

Asset::save()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 24
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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