Passed
Push — develop ( 399d1e...2d2a1d )
by Andrew
06:19 queued 36s
created

OptimizedImage::getPlaceholderImage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
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
     *
383
     * @param array $linkAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
384
     *
385
     * @return \Twig\Markup
386
     */
387
    public function linkPreloadTag($linkAttrs = [])
388
    {
389
        // Any web browser that supports link rel="preload" as="image" also supports webp, so prefer that
390
        $srcset = $this->optimizedImageUrls;
391
        if (!empty($this->optimizedWebPImageUrls)) {
392
            $srcset = $this->optimizedWebPImageUrls;
393
        }
394
        // Merge the passed in options with the tag attributes
395
        $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...
396
            'rel' => 'preload',
397
            'as' => 'image',
398
            'href' => reset($srcset),
399
            'imagesrcset' => $this->getSrcsetFromArray($srcset),
400
            'imagesizes' => '100vw',
401
        ],
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...
402
            $linkAttrs
403
        );
404
        // Remove any empty attributes
405
        $attrs = array_filter($attrs);
406
        // Render the tag
407
        $tag = Html::tag('link', '', $attrs);
408
409
        return Template::raw($tag);
410
    }
411
412
    /**
413
     * Generate a complete <img> tag for this OptimizedImages model
414
     *
415
     * @param false|string $lazyLoad
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
416
     * @param array $imgAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
417
     *
418
     * @return \Twig\Markup
419
     */
420
    public function imgTag($lazyLoad = false, $imgAttrs = [])
421
    {
422
        // Merge the passed in options with the tag attributes
423
        $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...
424
                'class' => '',
425
                'style' => '',
426
                'width' => $this->placeholderWidth,
427
                'height' => $this->placeholderHeight,
428
                'src' => reset($this->optimizedImageUrls),
429
                'srcset' => $this->getSrcsetFromArray($this->optimizedImageUrls),
430
                'sizes' => '100vw',
431
                'loading' => $lazyLoad,
432
            ],
433
            $imgAttrs
434
        );
435
        // Handle lazy loading
436
        if ($lazyLoad) {
437
            $attrs = $this->swapLazyLoadAttrs($lazyLoad, $attrs);
438
        }
439
        // Remove any empty attributes
440
        $attrs = array_filter($attrs);
441
        // Render the tag
442
        $tag = Html::tag('img', '', $attrs);
443
444
        return Template::raw($tag);
445
    }
446
447
    /**
448
     * Generate a complete <picture> tag for this OptimizedImages model
449
     *
450
     * @param false $lazyLoad
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
451
     * @param array $pictureAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
452
     * @param array $srcsetAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
453
     * @param array $imgAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
454
     *
455
     * @return \Twig\Markup
456
     */
457
    public function pictureTag($lazyLoad = false, $pictureAttrs = [], $srcsetAttrs = [], $imgAttrs = [])
458
    {
459
        $content = '';
460
        // Handle the webp srcset
461
        if (!empty($this->optimizedWebPImageUrls)) {
462
            // Merge the passed in options with the tag attributes
463
            $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...
464
                    'data-srcset' => $this->getSrcsetFromArray($this->optimizedWebPImageUrls),
465
                    'type' => 'image/webp',
466
                    'sizes' => '100vw',
467
                ],
468
                $srcsetAttrs
469
            );
470
            // Handle lazy loading
471
            if ($lazyLoad) {
0 ignored issues
show
introduced by
The condition $lazyLoad is always false.
Loading history...
472
                $attrs = $this->swapLazyLoadAttrs($lazyLoad, $attrs);
473
            }
474
            // Remove any empty attributes
475
            $attrs = array_filter($attrs);
476
            // Render the tag
477
            $content .= Html::tag('source', '', $attrs);
478
        }
479
        // Handle the regular srcset
480
        if (!empty($this->optimizedImageUrls)) {
481
            // Merge the passed in options with the tag attributes
482
            $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...
483
                    'data-srcset' => $this->getSrcsetFromArray($this->optimizedImageUrls),
484
                    'sizes' => '100vw',
485
                ],
486
                $srcsetAttrs
487
            );
488
            // Handle lazy loading
489
            if ($lazyLoad) {
0 ignored issues
show
introduced by
The condition $lazyLoad is always false.
Loading history...
490
                $attrs = $this->swapLazyLoadAttrs($lazyLoad, $attrs);
491
            }
492
            // Remove any empty attributes
493
            $attrs = array_filter($attrs);
494
            // Render the tag
495
            $content .= Html::tag('source', '', $attrs);
496
        }
497
        // Handle the img tag
498
        /** @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...
499
        $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...
500
                'class' => '',
501
                'style' => '',
502
                'width' => $this->placeholderWidth,
503
                'height' => $this->placeholderHeight,
504
                'src' => reset($this->optimizedImageUrls),
505
                'loading' => $lazyLoad,
506
            ],
507
            $imgAttrs
508
        );
509
        // Handle lazy loading
510
        if ($lazyLoad) {
0 ignored issues
show
introduced by
The condition $lazyLoad is always false.
Loading history...
511
            $attrs = $this->swapLazyLoadAttrs($lazyLoad, $attrs);
512
        }
513
        // Remove any empty attributes
514
        $attrs = array_filter($attrs);
515
        // Render the tag
516
        $content .= Html::tag('img', '', $attrs);
517
        // Merge the passed in options with the tag attributes
518
        $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...
519
            ],
520
            $pictureAttrs
521
        );
522
        // Remove any empty attributes
523
        $attrs = array_filter($attrs);
524
        // Render the tag
525
        $tag = Html::tag('picture', $content, $attrs);
526
527
        return Template::raw($tag);
528
    }
529
530
    /**
531
     * Return a base64-encoded placeholder image
532
     *
533
     * @return \Twig\Markup|null
534
     */
535
    public function placeholderImage()
536
    {
537
        $header = 'data:image/jpeg;base64,';
538
        if (!empty($this->placeholder)) {
539
            $content = $this->placeholder;
540
        } else {
541
            // At least return something
542
            return $this->defaultPlaceholderImage();
543
        }
544
545
        return Template::raw($header.rawurlencode($content));
546
    }
547
548
    /**
549
     * Getter for CraftQL
550
     *
551
     * @return string
552
     */
553
    public function getPlaceholderImage(): string
554
    {
555
        return (string)$this->placeholderImage();
556
    }
557
558
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
559
     * @return string
560
     */
561
    public function placeholderImageSize(): string
562
    {
563
        $placeholder = $this->placeholderImage();
564
        $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0;
565
566
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
567
    }
568
569
    /**
570
     * Return an SVG box as a placeholder image
571
     *
572
     * @param string|null $color
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
573
     *
574
     * @return \Twig\Markup|null
575
     */
576
    public function placeholderBox(string $color = null)
577
    {
578
        $width = $this->placeholderWidth ?? 1;
579
        $height = $this->placeholderHeight ?? 1;
580
        $color = $color ?? $this->colorPalette[0] ?? '#CCC';
581
582
        return Template::raw(ImageOptimize::$plugin->placeholder->generatePlaceholderBox($width, $height, $color));
583
    }
584
585
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
586
     * @param string|null $color
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
587
     *
588
     * @return string
589
     */
590
    public function getPlaceholderBox(string $color = null): string
591
    {
592
        return (string)$this->placeholderBox($color);
593
    }
594
595
    /**
596
     * Getter for CraftQL
597
     *
598
     * @return string
599
     */
600
    public function placeholderBoxSize(): string
601
    {
602
        $placeholder = $this->placeholderBox();
603
        $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0;
604
605
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
606
    }
607
608
    /**
609
     * Return a silhouette of the image as an SVG placeholder
610
     *
611
     * @return \Twig\Markup|null
612
     */
613
    public function placeholderSilhouette()
614
    {
615
        $header = 'data:image/svg+xml,';
616
        if (!empty($this->placeholderSvg)) {
617
            $content = $this->placeholderSvg;
618
        } else {
619
            // At least return something
620
            return $this->defaultPlaceholderImage();
621
        }
622
623
        return Template::raw($header.$content);
624
    }
625
626
    /**
627
     * Getter for CraftQL
628
     *
629
     * @return string
630
     */
631
    public function getPlaceholderSilhouette(): string
632
    {
633
        return (string)$this->placeholderSilhouette();
634
    }
635
636
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
637
     * @return string
638
     */
639
    public function placeholderSilhouetteSize(): string
640
    {
641
        $placeholder = $this->placeholderSilhouette();
642
        $contentLength = !empty(\strlen($placeholder)) ? \strlen($placeholder) : 0;
643
644
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
645
    }
646
647
    /**
648
     *  Get the file size of any remote resource (using curl),
649
     *  either in bytes or - default - as human-readable formatted string.
650
     *
651
     * @author  Stephan Schmitz <[email protected]>
652
     * @license MIT <http://eyecatchup.mit-license.org/>
653
     * @url     <https://gist.github.com/eyecatchup/f26300ffd7e50a92bc4d>
654
     *
655
     * @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...
656
     * @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...
657
     *                              formatted.
658
     * @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...
659
     *                              uses GET.
660
     *
661
     * @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...
662
     *                              or size in bytes (default: formatted).
663
     */
664
    public function getRemoteFileSize($url, $formatSize = true, $useHead = true)
665
    {
666
        // Get an absolute URL with protocol that curl will be happy with
667
        $url = UrlHelper::absoluteUrlWithProtocol($url);
668
        $ch = curl_init($url);
669
        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...
670
            CURLOPT_RETURNTRANSFER => 1,
671
            CURLOPT_FOLLOWLOCATION => 1,
672
            CURLOPT_SSL_VERIFYPEER => 0,
673
        ]);
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...
674
        if ($useHead) {
675
            curl_setopt($ch, CURLOPT_NOBODY, 1);
676
        }
677
        curl_exec($ch);
678
        // content-length of download (in bytes), read from Content-Length: field
679
        $contentLength = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
680
        curl_close($ch);
681
        // cannot retrieve file size, return "-1"
682
        if (!$contentLength) {
683
            return -1;
684
        }
685
        // return size in bytes
686
        if (!$formatSize) {
687
            return $contentLength;
688
        }
689
690
        return ImageOptimize::$plugin->optimize->humanFileSize($contentLength, 1);
691
    }
692
693
    // Protected Methods
694
    // =========================================================================
695
696
    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...
697
    {
698
        $subset = [];
699
        $index = 0;
700
        if (empty($this->variantSourceWidths)) {
701
            return $subset;
702
        }
703
        foreach ($this->variantSourceWidths as $variantSourceWidth) {
704
            $match = false;
705
            switch ($comparison) {
706
                case 'width':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
707
                    if ($variantSourceWidth == $width) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
708
                        $match = true;
709
                    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
710
                    break;
711
712
                case 'minwidth':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
713
                    if ($variantSourceWidth >= $width) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
714
                        $match = true;
715
                    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
716
                    break;
717
718
                case 'maxwidth':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
719
                    if ($variantSourceWidth <= $width) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
720
                        $match = true;
721
                    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
722
                    break;
723
            }
724
            if ($match) {
725
                $subset += array_slice($set, $index, 1, true);
726
            }
727
            $index++;
728
        }
729
730
        return $subset;
731
    }
732
733
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
734
     * @param array $array
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
735
     * @param bool  $dpr
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
736
     *
737
     * @return string
738
     */
739
    protected function getSrcsetFromArray(array $array, bool $dpr = false): string
740
    {
741
        $srcset = '';
742
        foreach ($array as $key => $value) {
743
            if ($dpr) {
744
                $descriptor = '1x';
745
                if (!empty($array[(int)$key / 2])) {
746
                    $descriptor = '2x';
747
                }
748
                if (!empty($array[(int)$key / 3])) {
749
                    $descriptor = '3x';
750
                }
751
            } else {
752
                $descriptor = $key.'w';
753
            }
754
            $srcset .= $value.' '.$descriptor.', ';
755
        }
756
        $srcset = rtrim($srcset, ', ');
757
758
        return $srcset;
759
    }
760
761
    /**
762
     * Return a default placeholder image
763
     *
764
     * @return \Twig\Markup
765
     */
766
    protected function defaultPlaceholderImage(): \Twig\Markup
767
    {
768
        $width = 1;
769
        $height = 1;
770
        $color = '#CCC';
771
772
        return Template::raw(ImageOptimize::$plugin->placeholder->generatePlaceholderBox($width, $height, $color));
773
    }
774
775
    /**
776
     * Swap the tag attributes to work with lazy loading
777
     *
778
     * @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...
Coding Style introduced by
Doc comment for parameter $attrs does not match actual variable name $lazyLoad
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
779
     * @param string $lazyLoad
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $lazyLoad does not match actual variable name $attrs
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
780
     * @return array
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
781
     */
782
    protected function swapLazyLoadAttrs(string $lazyLoad, array $attrs): array
783
    {
784
        if (isset($attrs['class'])) {
785
            $attrs['class'] = trim($attrs['class'] . ' lazyload');
786
        }
787
        if (!empty($attrs['loading'])) {
788
            $attrs['loading'] = 'lazy';
789
        }
790
        if (!empty($attrs['srcset'])) {
791
            $attrs['data-srcset'] = $attrs['srcset'];
792
            $attrs['srcset'] = '';
793
        }
794
        if (!empty($attrs['src'])) {
795
            $attrs['data-src'] = $attrs['src'];
796
            $attrs['src'] = $this->getLazyLoadSrc($lazyLoad);
797
            if (isset($attrs['style'])) {
798
                $attrs['style'] = trim(
799
                    $attrs['style'] .
800
                    'background-image:url(' . $this->getLazyLoadSrc($lazyLoad) . '); background-size: cover;'
801
                );
802
            }
803
        }
804
805
        return $attrs;
806
    }
807
808
    /**
809
     * Return a lazy loading placeholder image based on the passed in $lazyload setting
810
     *
811
     * @param string $lazyLoad
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
812
     * @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...
Coding Style introduced by
Superfluous parameter comment
Loading history...
813
     *
814
     * @return array
815
     */
816
    protected function getLazyLoadSrc(string $lazyLoad): string
817
    {
818
        $result = '';
819
        if (is_string($lazyLoad)) {
0 ignored issues
show
introduced by
The condition is_string($lazyLoad) is always true.
Loading history...
820
            $lazyLoad = strtolower($lazyLoad);
821
        }
822
        switch ($lazyLoad) {
823
            case 'image':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
824
                $result = $this->getPlaceholderImage();
825
                break;
826
            case 'silhouette':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
827
                $result = $this->getPlaceholderSilhouette();
828
                break;
829
            case 'color':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
830
                $result = $this->getPlaceholderBox($this->colorPalette[0] ?? null);
831
                break;
832
            default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
833
                $result = $this->getPlaceholderBox();
834
                break;
835
        }
836
837
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result returns the type string which is incompatible with the documented return type array.
Loading history...
838
    }
839
}
840