Passed
Push — markdown-responsive ( 66d0bb...dea121 )
by Arnaud
09:36 queued 05:00
created

Asset::resize()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 34
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

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