Passed
Push — feat/svg-dimensions ( 9c4bf5 )
by Arnaud
04:58 queued 11s
created

Asset::getSvgAttributes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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