Passed
Push — dependabot/composer/yosymfony/... ( ba9b85...52e1d3 )
by
unknown
03:32 queued 40s
created

Asset::getImageSize()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 11
rs 10
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\Config;
15
use Cecil\Exception\Exception;
16
use Cecil\Util;
17
use MatthiasMullie\Minify;
18
use ScssPhp\ScssPhp\Compiler;
19
use wapmorgan\Mp3Info\Mp3Info;
20
21
class Asset implements \ArrayAccess
22
{
23
    /** @var Builder */
24
    protected $builder;
25
    /** @var Config */
26
    protected $config;
27
    /** @var array */
28
    protected $data = [];
29
    /** @var bool */
30
    protected $fingerprinted = false;
31
    /** @var bool */
32
    protected $compiled = false;
33
    /** @var bool */
34
    protected $minified = false;
35
36
    /**
37
     * Creates an Asset from file.
38
     *
39
     * $options[
40
     *     'fingerprint' => false,
41
     *     'minify'      => false,
42
     * ];
43
     *
44
     * @param Builder      $builder
45
     * @param string|array $path
46
     * @param array|null   $options
47
     */
48
    public function __construct(Builder $builder, $path, array $options = null)
49
    {
50
        $this->builder = $builder;
51
        $this->config = $builder->getConfig();
52
        $path = is_array($path) ? $path : [$path];
53
54
        // handles options
55
        $fingerprint = (bool) $this->config->get('assets.fingerprint.enabled');
56
        $minify = (bool) $this->config->get('assets.minify.enabled');
57
        $filename = '';
58
        extract(is_array($options) ? $options : [], EXTR_IF_EXISTS);
59
60
        // load file(s)
61
        $prevType = '';
62
        $prevExt = '';
63
        foreach ($path as $p) {
64
            $file = $this->loadFile($p);
65
66
            // same type only
67
            if (!empty($prevType) && $prevType != $file['type']) {
68
                throw new Exception(\sprintf('Asset bundle works only for files with the same type.'));
69
            }
70
            // same extension only
71
            if (!empty($prevExt) && $prevExt != $file['ext']) {
72
                throw new Exception(\sprintf('Asset bundle works only for files with the same extension.'));
73
            }
74
75
            // set data
76
            $this->data['file'] = $file['filepath'];
77
            $this->data['path'] = $file['path'];
78
            $this->data['ext'] = $file['ext'];
79
            $this->data['type'] = $file['type'];
80
            $this->data['subtype'] = $file['subtype'];
81
            $this->data['size'] = $file['size'];
82
            $this->data['source'] = $file['content'];
83
            $this->data['content'] .= $file['content'];
84
85
            $prevType = $file['type'];
86
            $prevExt = $file['ext'];
87
        }
88
        // path to the bundled file
89
        if (count($path) > 1) {
90
            $this->data['path'] = $filename;
91
            if (empty($filename)) {
92
                switch ($this->data['ext']) {
93
                    case 'scss':
94
                    case 'css':
95
                        $this->data['path'] = 'styles.'.$file['ext'];
96
                        break;
97
                    case 'js':
98
                        $this->data['path'] = 'scripts.'.$file['ext'];
99
                        break;
100
                    default:
101
                        throw new Exception(\sprintf('Asset bundle supports "%s" files only.', 'scss, css and js'));
102
                        break;
103
                }
104
            }
105
        }
106
107
        // fingerprinting
108
        if ($fingerprint) {
109
            $this->fingerprint();
110
        }
111
        // compiling
112
        if ((bool) $this->config->get('assets.compile.enabled')) {
113
            $this->compile();
114
        }
115
        // minifying
116
        if ($minify) {
117
            $this->minify();
118
        }
119
    }
120
121
    /**
122
     * Returns Asset path.
123
     *
124
     * @return string
125
     */
126
    public function __toString(): string
127
    {
128
        return $this->data['path'];
129
    }
130
131
    /**
132
     * Fingerprints a file.
133
     *
134
     * @return self
135
     */
136
    public function fingerprint(): self
137
    {
138
        if ($this->fingerprinted) {
139
            return $this;
140
        }
141
142
        $fingerprint = hash('md5', $this->data['source']);
143
        $this->data['path'] = preg_replace(
144
            '/\.'.$this->data['ext'].'$/m',
145
            ".$fingerprint.".$this->data['ext'],
146
            $this->data['path']
147
        );
148
149
        $this->fingerprinted = true;
150
151
        return $this;
152
    }
153
154
    /**
155
     * Compiles a SCSS.
156
     *
157
     * @return self
158
     */
159
    public function compile(): self
160
    {
161
        if ($this->compiled) {
162
            return $this;
163
        }
164
165
        if ($this->data['ext'] != 'scss') {
166
            return $this;
167
        }
168
169
        $cache = new Cache($this->builder, 'assets');
170
        $cacheKey = $cache->createKeyFromAsset($this);
171
        if (!$cache->has($cacheKey)) {
172
            $scssPhp = new Compiler();
173
            // import path
174
            $scssPhp->addImportPath(Util::joinPath($this->config->getStaticPath()));
175
            $scssDir = $this->config->get('assets.compile.import') ?? [];
176
            $themes = $this->config->getTheme() ?? [];
177
            foreach ($scssDir as $dir) {
178
                $scssPhp->addImportPath(Util::joinPath($this->config->getStaticPath(), $dir));
179
                $scssPhp->addImportPath(Util::joinPath(dirname($this->data['file']), $dir));
180
                foreach ($themes as $theme) {
181
                    $scssPhp->addImportPath(Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir")));
182
                }
183
            }
184
            // output style
185
            $formatter = \sprintf(
186
                'ScssPhp\ScssPhp\Formatter\%s',
187
                ucfirst((string) $this->config->get('assets.compile.style'))
188
            );
189
            if (!class_exists($formatter)) {
190
                throw new Exception(\sprintf('Scss formatter "%s" doesn\'t exists.', $formatter));
191
            }
192
            $scssPhp->setFormatter($formatter);
193
            // variables
194
            $scssPhp->setVariables($this->config->get('assets.compile.variables') ?? []);
195
            $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']);
196
            $this->data['ext'] = 'css';
197
            $this->data['content'] = $scssPhp->compile($this->data['content']);
198
            $this->compiled = true;
199
            $cache->set($cacheKey, $this->data);
200
        }
201
        $this->data = $cache->get($cacheKey);
202
203
        return $this;
204
    }
205
206
    /**
207
     * Minifying a CSS or a JS.
208
     *
209
     * @return self
210
     */
211
    public function minify(): self
212
    {
213
        if ($this->minified) {
214
            return $this;
215
        }
216
217
        if ($this->data['ext'] == 'scss') {
218
            $this->compile();
219
        }
220
221
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
222
            return $this;
223
        }
224
225
        if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') {
226
            $this->minified;
227
228
            return $this;
229
        }
230
231
        $cache = new Cache($this->builder, 'assets');
232
        $cacheKey = $cache->createKeyFromAsset($this);
233
        if (!$cache->has($cacheKey)) {
234
            switch ($this->data['ext']) {
235
                case 'css':
236
                    $minifier = new Minify\CSS($this->data['content']);
237
                    break;
238
                case 'js':
239
                    $minifier = new Minify\JS($this->data['content']);
240
                    break;
241
                default:
242
                    throw new Exception(sprintf('Not able to minify "%s"', $this->data['path']));
243
            }
244
            $this->data['path'] = preg_replace(
245
                '/\.'.$this->data['ext'].'$/m',
246
                '.min.'.$this->data['ext'],
247
                $this->data['path']
248
            );
249
            $this->data['content'] = $minifier->minify();
250
            $this->minified = true;
251
            $cache->set($cacheKey, $this->data);
252
        }
253
        $this->data = $cache->get($cacheKey);
254
255
        return $this;
256
    }
257
258
    /**
259
     * Implements \ArrayAccess.
260
     */
261
    public function offsetSet($offset, $value)
262
    {
263
        if (!is_null($offset)) {
264
            $this->data[$offset] = $value;
265
        }
266
    }
267
268
    /**
269
     * Implements \ArrayAccess.
270
     */
271
    public function offsetExists($offset)
272
    {
273
        return isset($this->data[$offset]);
274
    }
275
276
    /**
277
     * Implements \ArrayAccess.
278
     */
279
    public function offsetUnset($offset)
280
    {
281
        unset($this->data[$offset]);
282
    }
283
284
    /**
285
     * Implements \ArrayAccess.
286
     */
287
    public function offsetGet($offset)
288
    {
289
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
290
    }
291
292
    /**
293
     * Hashing content of an asset with the specified algo, sha384 by default.
294
     * Used for SRI (Subresource Integrity).
295
     *
296
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
297
     *
298
     * @return string
299
     */
300
    public function getIntegrity(string $algo = 'sha384'): string
301
    {
302
        return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
303
    }
304
305
    /**
306
     * Returns the width of an image.
307
     *
308
     * @return false|int
309
     */
310
    public function getWidth()
311
    {
312
        if (false === $size = $this->getImageSize()) {
313
            return false;
314
        }
315
316
        return $size[0];
317
    }
318
319
    /**
320
     * Returns the height of an image.
321
     *
322
     * @return false|int
323
     */
324
    public function getHeight()
325
    {
326
        if (false === $size = $this->getImageSize()) {
327
            return false;
328
        }
329
330
        return $size[1];
331
    }
332
333
    /**
334
     * Returns MPF3 file infos.
335
     *
336
     * @see https://github.com/wapmorgan/Mp3Info
337
     *
338
     * @return Mp3Info
339
     */
340
    public function getAudio(): Mp3Info
341
    {
342
        return new Mp3Info($this->data['file']);
343
    }
344
345
    /**
346
     * Saves file.
347
     * Note: a file from `static/` with the same name will be overridden.
348
     *
349
     * @throws Exception
350
     *
351
     * @return void
352
     */
353
    public function save(): void
354
    {
355
        $file = Util::joinFile($this->config->getOutputPath(), $this->data['path']);
356
        if (!$this->builder->getBuildOptions()['dry-run']) {
357
            try {
358
                Util::getFS()->dumpFile($file, $this->data['content']);
359
            } catch (\Symfony\Component\Filesystem\Exception\IOException $e) {
360
                throw new Exception(\sprintf('Can\'t save asset "%s"', $this->data['path']));
361
            }
362
        }
363
    }
364
365
    /**
366
     * Load file data.
367
     *
368
     * @param string $path
369
     *
370
     * @return array
371
     */
372
    private function loadFile(string $path): array
373
    {
374
        $file = [];
375
        $path = '/'.ltrim($path, '/');
376
377
        if (false === $filePath = $this->findFile($path)) {
378
            throw new Exception(sprintf('Asset file "%s" doesn\'t exist.', $path));
379
        }
380
381
        $pathinfo = pathinfo($path);
382
        list($type, $subtype) = Util::getMimeType($filePath);
383
        $content = file_get_contents($filePath);
384
385
        $file['filepath'] = $filePath;
386
        $file['path'] = $path;
387
        $file['ext'] = $pathinfo['extension'];
388
        $file['type'] = $type;
389
        $file['subtype'] = $subtype;
390
        $file['size'] = filesize($filePath);
391
        $file['content'] = $content;
392
393
        return $file;
394
    }
395
396
    /**
397
     * Try to find a static file (in site or theme(s)) if exists or returns false.
398
     *
399
     * @param string $path
400
     *
401
     * @return string|false
402
     */
403
    private function findFile(string $path)
404
    {
405
        $filePath = Util::joinFile($this->config->getStaticPath(), $path);
406
        if (Util::getFS()->exists($filePath)) {
407
            return $filePath;
408
        }
409
410
        // checks in each theme
411
        foreach ($this->config->getTheme() as $theme) {
412
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
413
            if (Util::getFS()->exists($filePath)) {
414
                return $filePath;
415
            }
416
        }
417
418
        return false;
419
    }
420
421
    /**
422
     * Returns image size informations.
423
     *
424
     * See https://www.php.net/manual/function.getimagesize.php
425
     *
426
     * @return false|array
427
     */
428
    private function getImageSize()
429
    {
430
        if (!$this->data['type'] == 'image') {
431
            return false;
432
        }
433
434
        if (false === $size = getimagesizefromstring($this->data['content'])) {
435
            return false;
436
        }
437
438
        return $size;
439
    }
440
}
441