Passed
Push — v1 ( d8ddb5...d163cc )
by Andrew
12:26 queued 04:57
created

OptimizedImage::srcsetMinWidthWebp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
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 craft\helpers\Html;
14
use nystudio107\imageoptimize\ImageOptimize;
15
use nystudio107\imageoptimize\helpers\UrlHelper;
16
use nystudio107\imageoptimize\helpers\Color as ColorHelper;
17
18
use craft\helpers\Template;
19
use craft\base\Model;
20
use craft\validators\ArrayValidator;
21
22
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
23
 * @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...
24
 * @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...
25
 * @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...
26
 */
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...
27
class OptimizedImage extends Model
28
{
29
    // Public Properties
30
    // =========================================================================
31
32
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
33
     * @var string[] An array of optimized image variant URLs
34
     */
35
    public $optimizedImageUrls = [];
36
37
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
38
     * @var string[] An array of optimized .webp image variant URLs
39
     */
40
    public $optimizedWebPImageUrls = [];
41
42
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
43
     * @var int[] An array of the widths of the optimized image variants
44
     */
45
    public $variantSourceWidths = [];
46
47
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
48
     * @var int[] An array of the heights of the optimized image variants
49
     */
50
    public $variantHeights = [];
51
52
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
53
     * @var float[] An array of the x,y image focal point coords, ranging from 0.0 to 1.0
54
     */
55
    public $focalPoint;
56
57
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
58
     * @var int The width of the original source image
59
     */
60
    public $originalImageWidth;
61
62
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
63
     * @var int The height of the original source image
64
     */
65
    public $originalImageHeight;
66
67
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
68
     * @var string The base64 encoded placeholder LQIP image
69
     */
70
    public $placeholder = '';
71
72
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
73
     * @var string The base64 encoded placeholder LQIP SVG image
74
     */
75
    public $placeholderSvg = '';
76
77
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
78
     * @var string[] An array the 5 most dominant colors in the image
79
     */
80
    public $colorPalette = [];
81
82
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
83
     * @var int The overall lightness of the image, from 0..100
84
     */
85
    public $lightness;
86
87
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
88
     * @var int The width of the placeholder image
89
     */
90
    public $placeholderWidth;
91
92
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
93
     * @var int The height of the placeholder image
94
     */
95
    public $placeholderHeight;
96
97
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
98
     * @var string[] An array of errors logged when generating the image transforms
99
     */
100
    public $stickyErrors = [];
101
102
    // Public Methods
103
    // =========================================================================
104
105
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
106
     * @inheritdoc
107
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
108
    public function rules(): array
109
    {
110
        return [
111
            ['optimizedImageUrls', ArrayValidator::class],
112
            ['optimizedWebPImageUrls', ArrayValidator::class],
113
            ['variantSourceWidths', ArrayValidator::class],
114
            ['variantHeights', ArrayValidator::class],
115
            ['focalPoint', 'safe'],
116
            ['originalImageWidth', 'integer'],
117
            ['originalImageHeight', 'integer'],
118
            ['placeholder', 'string'],
119
            ['placeholderSvg', 'string'],
120
            ['colorPalette', ArrayValidator::class],
121
            ['placeholderWidth', 'integer'],
122
            ['placeholderHeight', 'integer'],
123
            ['stickyErrors', ArrayValidator::class],
124
        ];
125
    }
126
127
    /**
128
     * Return the first image variant URL or the specific one passed in via
129
     * $width
130
     *
131
     * @param int $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
132
     *
133
     * @return \Twig\Markup|null
134
     */
135
    public function src(int $width = 0): string
136
    {
137
        if (empty($width)) {
138
            return Template::raw(reset($this->optimizedImageUrls));
139
        }
140
141
        return Template::raw($this->optimizedImageUrls[$width] ?? '');
142
    }
143
144
    /**
145
     * Getter for CraftQL
146
     *
147
     * @param int $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
148
     *
149
     * @return null|string|\Twig\Markup
150
     */
151
    public function getSrc(int $width = 0): string
152
    {
153
        return $this->src($width);
154
    }
155
156
    /**
157
     * Return a string of image URLs and their sizes
158
     *
159
     * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw
160
     *                  srcsets
161
     *
162
     * @return \Twig\Markup|null
163
     */
164
    public function srcset(bool $dpr = false): string
165
    {
166
        return Template::raw($this->getSrcsetFromArray($this->optimizedImageUrls, $dpr));
167
    }
168
169
    /**
170
     * Getter for CraftQL
171
     *
172
     * @param bool $dpr
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
173
     *
174
     * @return string
175
     */
176
    public function getSrcset(bool $dpr = false): string
177
    {
178
        return $this->srcset($dpr);
179
    }
180
    /**
181
     * Return a string of image URLs and their sizes that match $width
182
     *
183
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
184
     * @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...
185
     *                  srcsets
186
     *
187
     * @return \Twig\Markup|null
188
     */
189
    public function srcsetWidth(int $width, bool $dpr = false): string
190
    {
191
        $subset = $this->getSrcsetSubsetArray($this->optimizedImageUrls, $width, 'width');
192
193
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
194
    }
195
196
    /**
197
     * Return a string of image URLs and their sizes that are at least $width
198
     * or larger
199
     *
200
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
201
     * @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...
202
     *                  srcsets
203
     *
204
     * @return \Twig\Markup|null
205
     */
206
    public function srcsetMinWidth(int $width, bool $dpr = false): string
207
    {
208
        $subset = $this->getSrcsetSubsetArray($this->optimizedImageUrls, $width, 'minwidth');
209
210
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
211
    }
212
213
    /**
214
     * Return a string of image URLs and their sizes that are $width or smaller
215
     *
216
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
217
     * @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...
218
     *                  srcsets
219
     *
220
     * @return \Twig\Markup|null
221
     */
222
    public function srcsetMaxWidth(int $width, bool $dpr = false): string
223
    {
224
        $subset = $this->getSrcsetSubsetArray($this->optimizedImageUrls, $width, 'maxwidth');
225
226
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
227
    }
228
229
    /**
230
     * Return the first webp image variant URL or the specific one passed in
231
     * via $width
232
     *
233
     * @param int $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
234
     *
235
     * @return \Twig\Markup|null
236
     */
237
    public function srcWebp(int $width = 0): string
238
    {
239
        if (empty($width)) {
240
            return Template::raw(reset($this->optimizedWebPImageUrls));
241
        }
242
243
        return Template::raw($this->optimizedWebPImageUrls[$width] ?? '');
244
    }
245
246
    /**
247
     * Getter for CraftQL
248
     *
249
     * @param int $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
250
     *
251
     * @return string
252
     */
253
    public function getSrcWebp(int $width = 0): string
254
    {
255
        return $this->srcWebp($width);
256
    }
257
258
    /**
259
     * Return a string of webp image URLs and their sizes
260
     *
261
     * @param bool $dpr Whether to generate 1x, 2x srcsets vs the normal XXXw
262
     *                  srcsets
263
     *
264
     * @return \Twig\Markup|null
265
     */
266
    public function srcsetWebp(bool $dpr = false): string
267
    {
268
        return Template::raw($this->getSrcsetFromArray($this->optimizedWebPImageUrls, $dpr));
269
    }
270
271
    /**
272
     * Getter for CraftQL
273
     *
274
     * @param bool $dpr
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
275
     *
276
     * @return string
277
     */
278
    public function getSrcsetWebp(bool $dpr = false): string
279
    {
280
        return $this->srcsetWebp($dpr);
281
    }
282
283
    /**
284
     * Return a string of webp image URLs and their sizes that match $width
285
     *
286
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
287
     * @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...
288
     *                  srcsets
289
     *
290
     * @return \Twig\Markup|null
291
     */
292
    public function srcsetWidthWebp(int $width, bool $dpr = false): string
293
    {
294
        $subset = $this->getSrcsetSubsetArray($this->optimizedWebPImageUrls, $width, 'width');
295
296
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
297
    }
298
299
    /**
300
     * Return a string of webp image URLs and their sizes that are at least
301
     * $width or larger
302
     *
303
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
304
     * @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...
305
     *                  srcsets
306
     *
307
     * @return \Twig\Markup|null
308
     */
309
    public function srcsetMinWidthWebp(int $width, bool $dpr = false): string
310
    {
311
        $subset = $this->getSrcsetSubsetArray($this->optimizedWebPImageUrls, $width, 'minwidth');
312
313
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
314
    }
315
316
    /**
317
     * Return a string of webp image URLs and their sizes that are $width or
318
     * smaller
319
     *
320
     * @param int  $width
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
321
     * @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...
322
     *                  srcsets
323
     *
324
     * @return \Twig\Markup|null
325
     */
326
    public function srcsetMaxWidthWebp(int $width, bool $dpr = false): string
327
    {
328
        $subset = $this->getSrcsetSubsetArray($this->optimizedWebPImageUrls, $width, 'maxwidth');
329
330
        return Template::raw($this->getSrcsetFromArray($subset, $dpr));
331
    }
332
333
    /**
334
     * Work around issues with `<img srcset>` returning sizes larger than are
335
     * available as per:
336
     * https://medium.com/@MRWwebDesign/responsive-images-the-sizes-attribute-and-unexpected-image-sizes-882a2eadb6db
337
     *
338
     * @return int
339
     */
340
    public function maxSrcsetWidth(): int
341
    {
342
        $result = 0;
343
        if (!empty($this->optimizedImageUrls)) {
344
            $tempArray = $this->optimizedImageUrls;
345
            ksort($tempArray, SORT_NUMERIC);
346
347
            $keys = array_keys($tempArray);
348
            $result = end($keys);
349
        }
350
351
        return $result;
352
    }
353
354
    /**
355
     * Getter for CraftQL
356
     *
357
     * @return int
358
     */
359
    public function getMaxSrcsetWidth(): int
360
    {
361
        return $this->maxSrcsetWidth();
362
    }
363
364
    /**
365
     * Return the colors as an array of RGB colors
366
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
367
    public function colorPaletteRgb(): array
368
    {
369
        $colors = [];
370
371
        foreach ($this->colorPalette as $color) {
372
            if (!empty($color)) {
373
                $colors[] = ColorHelper::HTMLToRGB($color);
374
            }
375
        }
376
377
        return $colors;
378
    }
379
380
    /**
381
     * Generate a complete <link rel="preload"> tag for this OptimizedImages model
382
     * ref: https://web.dev/preload-responsive-images/#imagesrcset-and-imagesizes
383
     *
384
     * @param array $linkAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
385
     *
386
     * @return \Twig\Markup
387
     */
388
    public function linkPreloadTag($linkAttrs = [])
389
    {
390
        // Any web browser that supports link rel="preload" as="image" also supports webp, so prefer that
391
        $srcset = $this->optimizedImageUrls;
392
        if (!empty($this->optimizedWebPImageUrls)) {
393
            $srcset = $this->optimizedWebPImageUrls;
394
        }
395
        // Merge the passed in options with the tag attributes
396
        $attrs = array_merge([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
397
            'rel' => 'preload',
398
            'as' => 'image',
399
            'href' => reset($srcset),
400
            'imagesrcset' => $this->getSrcsetFromArray($srcset),
401
            'imagesizes' => '100vw',
402
        ],
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 8.
Loading history...
403
            $linkAttrs
404
        );
405
        // Remove any empty attributes
406
        $attrs = array_filter($attrs);
407
        // Render the tag
408
        $tag = Html::tag('link', '', $attrs);
409
410
        return Template::raw($tag);
411
    }
412
413
    /**
414
     * Generate a complete <img> tag for this OptimizedImages model
415
     *
416
     * @param string $loading 'eager', 'lazy', 'lazySizes', 'lazySizesFallback'
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
417
     * @param string $placeHolder 'box', 'color', 'image', 'silhouette'
418
     * @param array $imgAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
419
     *
420
     * @return \Twig\Markup
421
     */
422
    public function imgTag($loading = 'eager', $placeHolder = 'box', $imgAttrs = [])
423
    {
424
        // Merge the passed in options with the tag attributes
425
        $attrs = array_merge([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
426
                'class' => '',
427
                'style' => '',
428
                'width' => $this->placeholderWidth,
429
                'height' => $this->placeholderHeight,
430
                'src' => reset($this->optimizedImageUrls),
431
                'srcset' => $this->getSrcsetFromArray($this->optimizedImageUrls),
432
                'sizes' => '100vw',
433
                'loading' => '',
434
            ],
435
            $imgAttrs
436
        );
437
        // Handle lazy loading
438
        if ($loading !== 'eager') {
439
            $attrs = $this->swapLazyLoadAttrs($loading, $placeHolder, $attrs);
440
        }
441
        // Remove any empty attributes
442
        $attrs = array_filter($attrs);
443
        // Render the tag
444
        $tag = Html::tag('img', '', $attrs);
445
446
        return Template::raw($tag);
447
    }
448
449
    /**
450
     * Generate a complete <picture> tag for this OptimizedImages model
451
     *
452
     * @param string $loading 'eager', 'lazy', 'lazySizes', 'lazySizesFallback'
0 ignored issues
show
Coding Style introduced by
Expected 6 spaces after parameter name; 1 found
Loading history...
453
     * @param string $placeHolder 'box', 'color', 'image', 'silhouette'
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
454
     * @param array $pictureAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
455
     * @param array $srcsetAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
456
     * @param array $imgAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
457
     *
458
     * @return \Twig\Markup
459
     */
460
    public function pictureTag($loading = 'eager', $placeHolder = 'box', $pictureAttrs = [], $srcsetAttrs = [], $imgAttrs = [])
461
    {
462
        $content = '';
463
        // Handle the webp srcset
464
        if (!empty($this->optimizedWebPImageUrls)) {
465
            // Merge the passed in options with the tag attributes
466
            $attrs = array_merge([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
467
                    'srcset' => $this->getSrcsetFromArray($this->optimizedWebPImageUrls),
468
                    'type' => 'image/webp',
469
                    'sizes' => '100vw',
470
                ],
471
                $srcsetAttrs
472
            );
473
            // Handle lazy loading
474
            if ($loading !== 'eager') {
475
                $attrs = $this->swapLazyLoadAttrs($loading, $placeHolder, $attrs);
476
            }
477
            // Remove any empty attributes
478
            $attrs = array_filter($attrs);
479
            // Render the tag
480
            $content .= Html::tag('source', '', $attrs);
481
        }
482
        // Handle the regular srcset
483
        if (!empty($this->optimizedImageUrls)) {
484
            // Merge the passed in options with the tag attributes
485
            $attrs = array_merge([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
486
                    'srcset' => $this->getSrcsetFromArray($this->optimizedImageUrls),
487
                    'sizes' => '100vw',
488
                ],
489
                $srcsetAttrs
490
            );
491
            // Handle lazy loading
492
            if ($loading !== 'eager') {
493
                $attrs = $this->swapLazyLoadAttrs($loading, $placeHolder, $attrs);
494
            }
495
            // Remove any empty attributes
496
            $attrs = array_filter($attrs);
497
            // Render the tag
498
            $content .= Html::tag('source', '', $attrs);
499
        }
500
        // Handle the img tag
501
        /** @noinspection SuspiciousAssignmentsInspection */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
502
        $attrs = array_merge([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
503
                'class' => '',
504
                'style' => '',
505
                'width' => $this->placeholderWidth,
506
                'height' => $this->placeholderHeight,
507
                'src' => reset($this->optimizedImageUrls),
508
                'loading' => '',
509
            ],
510
            $imgAttrs
511
        );
512
        // Handle lazy loading
513
        if ($loading !== 'eager') {
514
            $attrs = $this->swapLazyLoadAttrs($loading, $placeHolder, $attrs);
515
        }
516
        // Remove any empty attributes
517
        $attrs = array_filter($attrs);
518
        // Render the tag
519
        $content .= Html::tag('img', '', $attrs);
520
        // Merge the passed in options with the tag attributes
521
        $attrs = array_merge([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
522
            ],
523
            $pictureAttrs
524
        );
525
        // Remove any empty attributes
526
        $attrs = array_filter($attrs);
527
        // Render the tag
528
        $tag = Html::tag('picture', $content, $attrs);
529
530
        return Template::raw($tag);
531
    }
532
533
    /**
534
     * Return a base64-encoded placeholder image
535
     *
536
     * @return \Twig\Markup|null
537
     */
538
    public function placeholderImage()
539
    {
540
        $header = 'data:image/jpeg;base64,';
541
        if (!empty($this->placeholder)) {
542
            $content = $this->placeholder;
543
        } else {
544
            // At least return something
545
            return $this->defaultPlaceholderImage();
546
        }
547
548
        return Template::raw($header.rawurlencode($content));
549
    }
550
551
    /**
552
     * Getter for CraftQL
553
     *
554
     * @return string
555
     */
556
    public function getPlaceholderImage(): string
557
    {
558
        return (string)$this->placeholderImage();
559
    }
560
561
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
562
     * @return string
563
     */
564
    public function placeholderImageSize(): string
565
    {
566
        $placeholder = $this->placeholderImage();
567
        $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0;
568
569
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
570
    }
571
572
    /**
573
     * Return an SVG box as a placeholder image
574
     *
575
     * @param string|null $color
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
576
     *
577
     * @return \Twig\Markup|null
578
     */
579
    public function placeholderBox(string $color = null)
580
    {
581
        $width = $this->placeholderWidth ?? 1;
582
        $height = $this->placeholderHeight ?? 1;
583
        $color = $color ?? $this->colorPalette[0] ?? '#CCC';
584
585
        return Template::raw(ImageOptimize::$plugin->placeholder->generatePlaceholderBox($width, $height, $color));
586
    }
587
588
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
589
     * @param string|null $color
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
590
     *
591
     * @return string
592
     */
593
    public function getPlaceholderBox(string $color = null): string
594
    {
595
        return (string)$this->placeholderBox($color);
596
    }
597
598
    /**
599
     * Getter for CraftQL
600
     *
601
     * @return string
602
     */
603
    public function placeholderBoxSize(): string
604
    {
605
        $placeholder = $this->placeholderBox();
606
        $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0;
607
608
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
609
    }
610
611
    /**
612
     * Return a silhouette of the image as an SVG placeholder
613
     *
614
     * @return \Twig\Markup|null
615
     */
616
    public function placeholderSilhouette()
617
    {
618
        $header = 'data:image/svg+xml,';
619
        if (!empty($this->placeholderSvg)) {
620
            $content = $this->placeholderSvg;
621
        } else {
622
            // At least return something
623
            return $this->defaultPlaceholderImage();
624
        }
625
626
        return Template::raw($header.$content);
627
    }
628
629
    /**
630
     * Getter for CraftQL
631
     *
632
     * @return string
633
     */
634
    public function getPlaceholderSilhouette(): string
635
    {
636
        return (string)$this->placeholderSilhouette();
637
    }
638
639
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
640
     * @return string
641
     */
642
    public function placeholderSilhouetteSize(): string
643
    {
644
        $placeholder = $this->placeholderSilhouette();
645
        $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0;
646
647
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
648
    }
649
650
    /**
651
     *  Get the file size of any remote resource (using curl),
652
     *  either in bytes or - default - as human-readable formatted string.
653
     *
654
     * @author  Stephan Schmitz <[email protected]>
655
     * @license MIT <http://eyecatchup.mit-license.org/>
656
     * @url     <https://gist.github.com/eyecatchup/f26300ffd7e50a92bc4d>
657
     *
658
     * @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...
659
     * @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...
660
     *                              formatted.
661
     * @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...
662
     *                              uses GET.
663
     *
664
     * @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...
665
     *                              or size in bytes (default: formatted).
666
     */
667
    public function getRemoteFileSize($url, $formatSize = true, $useHead = true)
668
    {
669
        // Get an absolute URL with protocol that curl will be happy with
670
        $url = UrlHelper::absoluteUrlWithProtocol($url);
671
        $ch = curl_init($url);
672
        curl_setopt_array($ch, [
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
673
            CURLOPT_RETURNTRANSFER => 1,
674
            CURLOPT_FOLLOWLOCATION => 1,
675
            CURLOPT_SSL_VERIFYPEER => 0,
676
        ]);
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...
677
        if ($useHead) {
678
            curl_setopt($ch, CURLOPT_NOBODY, 1);
679
        }
680
        curl_exec($ch);
681
        // content-length of download (in bytes), read from Content-Length: field
682
        $contentLength = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
683
        curl_close($ch);
684
        // cannot retrieve file size, return "-1"
685
        if (!$contentLength) {
686
            return -1;
687
        }
688
        // return size in bytes
689
        if (!$formatSize) {
690
            return $contentLength;
691
        }
692
693
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
694
    }
695
696
    // Protected Methods
697
    // =========================================================================
698
699
    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...
700
    {
701
        $subset = [];
702
        $index = 0;
703
        if (empty($this->variantSourceWidths)) {
704
            return $subset;
705
        }
706
        foreach ($this->variantSourceWidths as $variantSourceWidth) {
707
            $match = false;
708
            switch ($comparison) {
709
                case 'width':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
710
                    if ($variantSourceWidth == $width) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
711
                        $match = true;
712
                    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
713
                    break;
714
715
                case 'minwidth':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
716
                    if ($variantSourceWidth >= $width) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
717
                        $match = true;
718
                    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
719
                    break;
720
721
                case 'maxwidth':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
722
                    if ($variantSourceWidth <= $width) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
723
                        $match = true;
724
                    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
725
                    break;
726
            }
727
            if ($match) {
728
                $subset += array_slice($set, $index, 1, true);
729
            }
730
            $index++;
731
        }
732
733
        return $subset;
734
    }
735
736
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
737
     * @param array $array
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
738
     * @param bool  $dpr
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
739
     *
740
     * @return string
741
     */
742
    protected function getSrcsetFromArray(array $array, bool $dpr = false): string
743
    {
744
        $srcset = '';
745
        foreach ($array as $key => $value) {
746
            if ($dpr) {
747
                $descriptor = '1x';
748
                if (!empty($array[(int)$key / 2])) {
749
                    $descriptor = '2x';
750
                }
751
                if (!empty($array[(int)$key / 3])) {
752
                    $descriptor = '3x';
753
                }
754
            } else {
755
                $descriptor = $key.'w';
756
            }
757
            $srcset .= $value.' '.$descriptor.', ';
758
        }
759
        $srcset = rtrim($srcset, ', ');
760
761
        return $srcset;
762
    }
763
764
    /**
765
     * Return a default placeholder image
766
     *
767
     * @return \Twig\Markup
768
     */
769
    protected function defaultPlaceholderImage(): \Twig\Markup
770
    {
771
        $width = 1;
772
        $height = 1;
773
        $color = '#CCC';
774
775
        return Template::raw(ImageOptimize::$plugin->placeholder->generatePlaceholderBox($width, $height, $color));
776
    }
777
778
    /**
779
     * Swap the tag attributes to work with lazy loading
780
     * ref: https://web.dev/native-lazy-loading/#how-do-i-handle-browsers-that-don't-yet-support-native-lazy-loading
781
     *
782
     * @param string $loading 'eager', 'lazy', 'lazySizes', 'lazySizesFallback'
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
783
     * @param string $placeHolder 'box', 'color', 'image', 'silhouette'
784
     * @param array $attrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
785
     *
786
     * @return array
787
     */
788
    protected function swapLazyLoadAttrs(string $loading, string $placeHolder, array $attrs): array
789
    {
790
        // Set the class and loading attributes
791
        if (isset($attrs['class'])) {
792
            $attrs['class'] = trim($attrs['class'] . ' lazyload');
793
        }
794
        // Set the style on this element to be the placeholder image as the background-image
795
        if (isset($attrs['style']) && !empty($attrs['src'])) {
796
            $attrs['style'] = trim(
797
                $attrs['style'] .
798
                'background-image:url(' . $this->getLazyLoadSrc($placeHolder) . '); background-size: cover;'
799
            );
800
        }
801
        // Handle attributes that lazy  and lazySizesFallback have in common
802
        switch ($loading) {
803
            case 'lazy':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
804
            case 'lazySizesFallback':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
805
            if (isset($attrs['loading'])) {
806
                    $attrs['loading'] = 'lazy';
807
                }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
Coding Style introduced by
Closing brace indented incorrectly; expected 12 spaces, found 16
Loading history...
808
                break;
809
            default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
810
                break;
811
        }
812
        // Handle attributes that lazySizes and lazySizesFallback have in common
813
        switch ($loading) {
814
            case 'lazySizes':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
815
            case 'lazySizesFallback':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
816
                // Only swap to data- attributes if they want the LazySizes fallback
817
                if (!empty($attrs['sizes'])) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
818
                    $attrs['data-sizes'] = $attrs['sizes'];
819
                    $attrs['sizes'] = '';
820
                }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
821
                if (!empty($attrs['srcset'])) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
822
                    $attrs['data-srcset'] = $attrs['srcset'];
823
                    $attrs['srcset'] = '';
824
                }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
825
                if (!empty($attrs['src'])) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
826
                    $attrs['data-src'] = $attrs['src'];
827
                    $attrs['src'] = $this->getLazyLoadSrc($placeHolder);
828
                }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
829
            break;
0 ignored issues
show
Coding Style introduced by
Case breaking statement indented incorrectly; expected 16 spaces, found 12
Loading history...
830
            default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
831
                break;
832
        }
833
834
        return $attrs;
835
    }
836
837
    /**
838
     * Return a lazy loading placeholder image based on the passed in $lazyload setting
839
     *
840
     * @param string $lazyLoad
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
841
     *
842
     * @return string
843
     */
844
    protected function getLazyLoadSrc(string $lazyLoad): string
845
    {
846
        $result = '';
847
        if (is_string($lazyLoad)) {
0 ignored issues
show
introduced by
The condition is_string($lazyLoad) is always true.
Loading history...
848
            $lazyLoad = strtolower($lazyLoad);
849
        }
850
        switch ($lazyLoad) {
851
            case 'image':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
852
                $result = $this->getPlaceholderImage();
853
                break;
854
            case 'silhouette':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
855
                $result = $this->getPlaceholderSilhouette();
856
                break;
857
            case 'color':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
858
                $result = $this->getPlaceholderBox($this->colorPalette[0] ?? null);
859
                break;
860
            default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
861
                $result = $this->getPlaceholderBox('#CCC');
862
                break;
863
        }
864
865
        return $result;
866
    }
867
}
868