Passed
Push — develop ( 37f497...ff1cbc )
by Andrew
11:52
created

OptimizedImage::placeholderBox()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 7
rs 10
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * Image Optimize plugin for Craft CMS 3.x
4
 *
5
 * Automatically optimize images after they've been transformed
6
 *
7
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @copyright Copyright (c) 2017 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
10
11
namespace nystudio107\imageoptimize\models;
12
13
use nystudio107\imageoptimize\ImageOptimize;
14
use nystudio107\imageoptimize\helpers\UrlHelper;
15
use nystudio107\imageoptimize\helpers\Color as ColorHelper;
16
17
use craft\helpers\Template;
18
use craft\base\Model;
19
use craft\validators\ArrayValidator;
20
21
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
22
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
23
 * @package   ImageOptimize
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
24
 * @since     1.2.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
25
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
26
class OptimizedImage extends Model
27
{
28
    // Public Properties
29
    // =========================================================================
30
31
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
32
     * @var string[] An array of optimized image variant URLs
33
     */
34
    public $optimizedImageUrls = [];
35
36
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
37
     * @var string[] An array of optimized .webp image variant URLs
38
     */
39
    public $optimizedWebPImageUrls = [];
40
41
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
42
     * @var int[] An array of the widths of the optimized image variants
43
     */
44
    public $variantSourceWidths = [];
45
46
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
47
     * @var int[] An array of the heights of the optimized image variants
48
     */
49
    public $variantHeights = [];
50
51
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
52
     * @var float[] An array of the x,y image focal point coords, ranging from 0.0 to 1.0
53
     */
54
    public $focalPoint;
55
56
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
57
     * @var int The width of the original source image
58
     */
59
    public $originalImageWidth;
60
61
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
62
     * @var int The height of the original source image
63
     */
64
    public $originalImageHeight;
65
66
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
67
     * @var string The base64 encoded placeholder LQIP image
68
     */
69
    public $placeholder = '';
70
71
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
72
     * @var string The base64 encoded placeholder LQIP SVG image
73
     */
74
    public $placeholderSvg = '';
75
76
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
77
     * @var string[] An array the 5 most dominant colors in the image
78
     */
79
    public $colorPalette = [];
80
81
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
82
     * @var int The overall lightness of the image, from 0..100
83
     */
84
    public $lightness;
85
86
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
87
     * @var int The width of the placeholder image
88
     */
89
    public $placeholderWidth;
90
91
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
92
     * @var int The height of the placeholder image
93
     */
94
    public $placeholderHeight;
95
96
    // Public Methods
97
    // =========================================================================
98
99
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
100
     * @inheritdoc
101
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
102
    public function rules(): array
103
    {
104
        return [
105
            ['optimizedImageUrls', ArrayValidator::class],
106
            ['optimizedWebPImageUrls', ArrayValidator::class],
107
            ['variantSourceWidths', ArrayValidator::class],
108
            ['variantHeights', ArrayValidator::class],
109
            ['focalPoint', 'safe'],
110
            ['originalImageWidth', 'integer'],
111
            ['originalImageHeight', 'integer'],
112
            ['placeholder', 'string'],
113
            ['placeholderSvg', 'string'],
114
            ['colorPalette', ArrayValidator::class],
115
            ['placeholderWidth', 'integer'],
116
            ['placeholderHeight', 'integer'],
117
        ];
118
    }
119
120
    /**
121
     * Return the first image variant URL or the specific one passed in via
122
     * $width
123
     *
124
     * @param int $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
125
     *
126
     * @return \Twig\Markup|null
127
     */
128
    public function src(int $width = 0): string
129
    {
130
        if (empty($width)) {
131
            return Template::raw(reset($this->optimizedImageUrls));
132
        }
133
134
        return Template::raw($this->optimizedImageUrls[$width] ?? '');
135
    }
136
137
    /**
138
     * Getter for CraftQL
139
     *
140
     * @param int $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
141
     *
142
     * @return null|string|\Twig\Markup
143
     */
144
    public function getSrc(int $width = 0): string
145
    {
146
        return $this->src($width);
147
    }
148
149
    /**
150
     * Return a string of image URLs and their sizes
151
     *
152
     * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw
153
     *                  srcsets
154
     *
155
     * @return \Twig\Markup|null
156
     */
157
    public function srcset(bool $dpr = false): string
158
    {
159
        return Template::raw($this->getSrcsetFromArray($this->optimizedImageUrls, $dpr));
160
    }
161
162
    /**
163
     * Getter for CraftQL
164
     *
165
     * @param bool $dpr
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
166
     *
167
     * @return string
168
     */
169
    public function getSrcset(bool $dpr = false): string
170
    {
171
        return $this->srcset($dpr);
172
    }
173
    /**
174
     * Return a string of image URLs and their sizes that match $width
175
     *
176
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
177
     * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
178
     *                  srcsets
179
     *
180
     * @return \Twig\Markup|null
181
     */
182
    public function srcsetWidth(int $width, bool $dpr = false): string
183
    {
184
        $subset = $this->getSrcsetSubsetArray($this->optimizedImageUrls, $width, 'width');
185
186
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
187
    }
188
189
    /**
190
     * Return a string of image URLs and their sizes that are at least $width
191
     * or larger
192
     *
193
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
194
     * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
195
     *                  srcsets
196
     *
197
     * @return \Twig\Markup|null
198
     */
199
    public function srcsetMinWidth(int $width, bool $dpr = false): string
200
    {
201
        $subset = $this->getSrcsetSubsetArray($this->optimizedImageUrls, $width, 'minwidth');
202
203
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
204
    }
205
206
    /**
207
     * Return a string of image URLs and their sizes that are $width or smaller
208
     *
209
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
210
     * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
211
     *                  srcsets
212
     *
213
     * @return \Twig\Markup|null
214
     */
215
    public function srcsetMaxWidth(int $width, bool $dpr = false): string
216
    {
217
        $subset = $this->getSrcsetSubsetArray($this->optimizedImageUrls, $width, 'maxwidth');
218
219
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
220
    }
221
222
    /**
223
     * Return the first webp image variant URL or the specific one passed in
224
     * via $width
225
     *
226
     * @param int $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
227
     *
228
     * @return \Twig\Markup|null
229
     */
230
    public function srcWebp(int $width = 0): string
231
    {
232
        if (empty($width)) {
233
            return Template::raw(reset($this->optimizedWebPImageUrls));
234
        }
235
236
        return Template::raw($this->optimizedWebPImageUrls[$width] ?? '');
237
    }
238
239
    /**
240
     * Getter for CraftQL
241
     *
242
     * @param int $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
243
     *
244
     * @return string
245
     */
246
    public function getSrcWebp(int $width = 0): string
247
    {
248
        return $this->srcWebp($width);
249
    }
250
251
    /**
252
     * Return a string of webp image URLs and their sizes
253
     *
254
     * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw
255
     *                  srcsets
256
     *
257
     * @return \Twig\Markup|null
258
     */
259
    public function srcsetWebp(bool $dpr = false): string
260
    {
261
        return Template::raw($this->getSrcsetFromArray($this->optimizedWebPImageUrls, $dpr));
262
    }
263
264
    /**
265
     * Getter for CraftQL
266
     *
267
     * @param bool $dpr
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
268
     *
269
     * @return string
270
     */
271
    public function getSrcsetWebp(bool $dpr = false): string
272
    {
273
        return $this->srcsetWebp($dpr);
274
    }
275
276
    /**
277
     * Return a string of webp image URLs and their sizes that match $width
278
     *
279
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
280
     * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
281
     *                  srcsets
282
     *
283
     * @return \Twig\Markup|null
284
     */
285
    public function srcsetWidthWebp(int $width, bool $dpr = false): string
286
    {
287
        $subset = $this->getSrcsetSubsetArray($this->optimizedWebPImageUrls, $width, 'width');
288
289
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
290
    }
291
292
    /**
293
     * Return a string of webp image URLs and their sizes that are at least
294
     * $width or larger
295
     *
296
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
297
     * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
298
     *                  srcsets
299
     *
300
     * @return \Twig\Markup|null
301
     */
302
    public function srcsetMinWidthWebp(int $width, bool $dpr = false): string
303
    {
304
        $subset = $this->getSrcsetSubsetArray($this->optimizedWebPImageUrls, $width, 'minwidth');
305
306
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
307
    }
308
309
    /**
310
     * Return a string of webp image URLs and their sizes that are $width or
311
     * smaller
312
     *
313
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
314
     * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
315
     *                  srcsets
316
     *
317
     * @return \Twig\Markup|null
318
     */
319
    public function srcsetMaxWidthWebp(int $width, bool $dpr = false): string
320
    {
321
        $subset = $this->getSrcsetSubsetArray($this->optimizedWebPImageUrls, $width, 'maxwidth');
322
323
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
324
    }
325
326
    /**
327
     * Work around issues with `<img srcset>` returning sizes larger than are
328
     * available as per:
329
     * https://medium.com/@MRWwebDesign/responsive-images-the-sizes-attribute-and-unexpected-image-sizes-882a2eadb6db
330
     *
331
     * @return int
332
     */
333
    public function maxSrcsetWidth(): int
334
    {
335
        $result = 0;
336
        if (!empty($this->optimizedImageUrls)) {
337
            $tempArray = $this->optimizedImageUrls;
338
            ksort($tempArray, SORT_NUMERIC);
339
340
            $keys = array_keys($tempArray);
341
            $result = end($keys);
342
        }
343
344
        return $result;
345
    }
346
347
    /**
348
     * Getter for CraftQL
349
     *
350
     * @return int
351
     */
352
    public function getMaxSrcsetWidth(): int
353
    {
354
        return $this->maxSrcsetWidth();
355
    }
356
357
    /**
358
     * Return the colors as an array of RGB colors
359
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
360
    public function colorPaletteRgb(): array
361
    {
362
        $colors = [];
363
364
        foreach ($this->colorPalette as $color) {
365
            if (!empty($color)) {
366
                $colors[] = ColorHelper::HTMLToRGB($color);
367
            }
368
        }
369
370
        return $colors;
371
    }
372
373
    /**
374
     * Return a base64-encoded placeholder image
375
     *
376
     * @return \Twig\Markup|null
377
     */
378
    public function placeholderImage()
379
    {
380
        $header = 'data:image/jpeg;base64,';
381
        if (!empty($this->placeholder)) {
382
            $content = $this->placeholder;
383
        } else {
384
            // At least return something
385
            return $this->defaultPlaceholderImage();
386
        }
387
388
        return Template::raw($header.rawurlencode($content));
389
    }
390
391
    /**
392
     * Getter for CraftQL
393
     *
394
     * @return string
395
     */
396
    public function getPlaceholderImage(): string
397
    {
398
        return (string)$this->placeholderImage();
399
    }
400
401
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
402
     * @return string
403
     */
404
    public function placeholderImageSize(): string
405
    {
406
        $placeholder = $this->placeholderImage();
407
        $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0;
408
409
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
410
    }
411
412
    /**
413
     * Return an SVG box as a placeholder image
414
     *
415
     * @param string|null $color
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
416
     *
417
     * @return \Twig\Markup|null
418
     */
419
    public function placeholderBox(string $color = null)
420
    {
421
        $width = $this->placeholderWidth ?? 1;
422
        $height = $this->placeholderHeight ?? 1;
423
        $color = $color ?? $this->colorPalette[0] ?? '#CCC';
424
425
        return Template::raw(ImageOptimize::$plugin->placeholder->generatePlaceholderBox($width, $height, $color));
426
    }
427
428
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
429
     * @param string|null $color
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
430
     *
431
     * @return string
432
     */
433
    public function getPlaceholderBox(string $color = null): string
434
    {
435
        return (string)$this->placeholderBox($color);
436
    }
437
438
    /**
439
     * Getter for CraftQL
440
     *
441
     * @return string
442
     */
443
    public function placeholderBoxSize(): string
444
    {
445
        $placeholder = $this->placeholderBox();
446
        $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0;
447
448
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
449
    }
450
451
    /**
452
     * Return a silhouette of the image as an SVG placeholder
453
     *
454
     * @return \Twig\Markup|null
455
     */
456
    public function placeholderSilhouette()
457
    {
458
        $header = 'data:image/svg+xml,';
459
        if (!empty($this->placeholderSvg)) {
460
            $content = $this->placeholderSvg;
461
        } else {
462
            // At least return something
463
            return $this->defaultPlaceholderImage();
464
        }
465
466
        return Template::raw($header.$content);
467
    }
468
469
    /**
470
     * Getter for CraftQL
471
     *
472
     * @return string
473
     */
474
    public function getPlaceholderSilhouette(): string
475
    {
476
        return (string)$this->placeholderSilhouette();
477
    }
478
479
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
480
     * @return string
481
     */
482
    public function placeholderSilhouetteSize(): string
483
    {
484
        $placeholder = $this->placeholderSilhouette();
485
        $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0;
486
487
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
488
    }
489
490
    /**
491
     *  Get the file size of any remote resource (using curl),
492
     *  either in bytes or - default - as human-readable formatted string.
493
     *
494
     * @author  Stephan Schmitz <[email protected]>
495
     * @license MIT <http://eyecatchup.mit-license.org/>
496
     * @url     <https://gist.github.com/eyecatchup/f26300ffd7e50a92bc4d>
497
     *
498
     * @param   string  $url        Takes the remote object's URL.
0 ignored issues
show
Coding Style introduced by
Parameter tags must be defined first in a doc comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 3
Loading history...
499
     * @param   boolean $formatSize Whether to return size in bytes or
0 ignored issues
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 3
Loading history...
500
     *                              formatted.
501
     * @param   boolean $useHead    Whether to use HEAD requests. If false,
0 ignored issues
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 3
Loading history...
502
     *                              uses GET.
503
     *
504
     * @return  int|mixed|string    Returns human-readable formatted size
0 ignored issues
show
Coding Style introduced by
Tag value for @return tag indented incorrectly; expected 1 spaces but found 2
Loading history...
505
     *                              or size in bytes (default: formatted).
506
     */
507
    public function getRemoteFileSize($url, $formatSize = true, $useHead = true)
508
    {
509
        // Get an absolute URL with protocol that curl will be happy with
510
        $url = UrlHelper::absoluteUrlWithProtocol($url);
511
        $ch = curl_init($url);
512
        curl_setopt_array($ch, [
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_setopt_array() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

512
        curl_setopt_array(/** @scrutinizer ignore-type */ $ch, [
Loading history...
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
513
            CURLOPT_RETURNTRANSFER => 1,
514
            CURLOPT_FOLLOWLOCATION => 1,
515
            CURLOPT_SSL_VERIFYPEER => 0,
516
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
517
        if ($useHead) {
518
            curl_setopt($ch, CURLOPT_NOBODY, 1);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_setopt() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

518
            curl_setopt(/** @scrutinizer ignore-type */ $ch, CURLOPT_NOBODY, 1);
Loading history...
519
        }
520
        curl_exec($ch);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

520
        curl_exec(/** @scrutinizer ignore-type */ $ch);
Loading history...
521
        // content-length of download (in bytes), read from Content-Length: field
522
        $contentLength = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_getinfo() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

522
        $contentLength = curl_getinfo(/** @scrutinizer ignore-type */ $ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
Loading history...
523
        curl_close($ch);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

523
        curl_close(/** @scrutinizer ignore-type */ $ch);
Loading history...
524
        // cannot retrieve file size, return "-1"
525
        if (!$contentLength) {
526
            return -1;
527
        }
528
        // return size in bytes
529
        if (!$formatSize) {
530
            return $contentLength;
531
        }
532
533
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
534
    }
535
536
    // Protected Methods
537
    // =========================================================================
538
539
    protected function getSrcsetSubsetArray(array $set, int $width, string $comparison): array
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
540
    {
541
        $subset = [];
542
        $index = 0;
543
        if (empty($this->variantSourceWidths)) {
544
            return $subset;
545
        }
546
        foreach ($this->variantSourceWidths as $variantSourceWidth) {
547
            $match = false;
548
            switch ($comparison) {
549
                case 'width':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
550
                    if ($variantSourceWidth == $width) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
551
                        $match = true;
552
                    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
553
                    break;
554
555
                case 'minwidth':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
556
                    if ($variantSourceWidth >= $width) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
557
                        $match = true;
558
                    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
559
                    break;
560
561
                case 'maxwidth':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
562
                    if ($variantSourceWidth <= $width) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
563
                        $match = true;
564
                    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
565
                    break;
566
            }
567
            if ($match) {
568
                $subset += array_slice($set, $index, 1, true);
569
            }
570
            $index++;
571
        }
572
573
        return $subset;
574
    }
575
576
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
577
     * @param array $array
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
578
     * @param bool  $dpr
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
579
     *
580
     * @return string
581
     */
582
    protected function getSrcsetFromArray(array $array, bool $dpr = false): string
583
    {
584
        $srcset = '';
585
        foreach ($array as $key => $value) {
586
            if ($dpr) {
587
                $descriptor = '1x';
588
                if (!empty($array[(int)$key / 2])) {
589
                    $descriptor = '2x';
590
                }
591
                if (!empty($array[(int)$key / 3])) {
592
                    $descriptor = '3x';
593
                }
594
            } else {
595
                $descriptor = $key.'w';
596
            }
597
            $srcset .= $value.' '.$descriptor.', ';
598
        }
599
        $srcset = rtrim($srcset, ', ');
600
601
        return $srcset;
602
    }
603
604
    /**
605
     * Return a default placeholder image
606
     *
607
     * @return \Twig\Markup
608
     */
609
    protected function defaultPlaceholderImage(): \Twig\Markup
610
    {
611
        $width = 1;
612
        $height = 1;
613
        $color = '#CCC';
614
615
        return Template::raw(ImageOptimize::$plugin->placeholder->generatePlaceholderBox($width, $height, $color));
616
    }
617
}
618