Completed
Push — master ( 6b3217...3aebab )
by Joschi
02:09
created

SourceSizeList::findImageCandidate()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 12
nc 3
nop 3
dl 0
loc 26
ccs 13
cts 13
cp 1
crap 3
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * responsive-images-css
5
 *
6
 * @category   Jkphl
7
 * @package    Jkphl\Respimgcss
8
 * @subpackage Jkphl\Respimgcss\Infrastructure
9
 * @author     Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright  Copyright © 2018 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license    http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2018 Joschi Kuphal <[email protected]> / @jkphl
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Jkphl\Respimgcss\Infrastructure;
38
39
use Jkphl\Respimgcss\Application\Contract\LengthFactoryInterface;
40
use Jkphl\Respimgcss\Application\Contract\SourceSizeListInterface;
41
use Jkphl\Respimgcss\Application\Model\SourceSize;
42
use Jkphl\Respimgcss\Application\Model\SourceSizeMediaCondition;
43
use Jkphl\Respimgcss\Domain\Contract\AbsoluteLengthInterface;
44
use Jkphl\Respimgcss\Domain\Contract\ImageCandidateInterface;
45
use Jkphl\Respimgcss\Domain\Contract\ImageCandidateSetInterface;
46
use Jkphl\Respimgcss\Domain\Contract\SourceSizeImageCandidateMatch;
47
use Jkphl\Respimgcss\Domain\Model\Css\MediaCondition;
48
use Jkphl\Respimgcss\Domain\Model\ImageCandidateMatch;
49
use Jkphl\Respimgcss\Ports\InvalidArgumentException;
50
51
/**
52
 * Sizes list
53
 *
54
 * @package    Jkphl\Respimgcss
55
 * @subpackage Jkphl\Respimgcss\Infrastructure
56
 * @see        http://w3c.github.io/html/semantics-embedded-content.html#ref-for-viewport-based-selection%E2%91%A0
57
 * @see        http://w3c.github.io/html/semantics-embedded-content.html#valid-source-size-list
58
 * @see        http://w3c.github.io/html/semantics-embedded-content.html#parse-a-sizes-attribute
59
 * @see        https://www.sitepoint.com/community/t/pixels-or-percentages-for-media-queries/37487
60
 */
61
class SourceSizeList extends \ArrayObject implements SourceSizeListInterface
62
{
63
    /**
64
     * Length factory
65
     *
66
     * @var LengthFactoryInterface
67
     */
68
    protected $lengthFactory;
69
70
    /**
71
     * Source size list constructor
72
     *
73
     * @param SourceSize[] $sourceSizes             Source sizes
74
     * @param LengthFactoryInterface $lengthFactory Length factory
75
     *
76
     * @throws InvalidArgumentException If the source size is invalid
77
     */
78 11
    public function __construct(array $sourceSizes, LengthFactoryInterface $lengthFactory)
79
    {
80
        // Run through all source sizes
81 11
        foreach ($sourceSizes as $sourceSize) {
82
            // If the source size is invalid
83 9
            if (!($sourceSize instanceof SourceSize)) {
84 1
                throw new InvalidArgumentException(
85 1
                    InvalidArgumentException::INVALID_SOURCE_SIZE_STR,
86 9
                    InvalidArgumentException::INVALID_SOURCE_SIZE
87
                );
88
            }
89
        }
90
91 10
        usort($sourceSizes, [$this, 'sortSourceSizes']);
92 10
        parent::__construct($sourceSizes);
93
94 10
        $this->lengthFactory = $lengthFactory;
95 10
    }
96
97
    /**
98
     * Find the optimum image candidate for a particular breakpoint
99
     *
100
     * @param ImageCandidateSetInterface $imageCandidates Image candidates
101
     * @param AbsoluteLengthInterface $breakpoint         Breakpoint
102
     * @param float $density                              Density
103
     *
104
     * @return SourceSizeImageCandidateMatch|null Image candidate match
105
     */
106 6
    public function findImageCandidate(
107
        ImageCandidateSetInterface $imageCandidates,
108
        AbsoluteLengthInterface $breakpoint,
109
        float $density
110
    ): ?SourceSizeImageCandidateMatch {
111
112
        // Run through the source sizes (from biggest to smallest)
113
        /** @var SourceSize $sourceSize */
114 6
        $lastMinimumWidth = null;
115 6
        foreach ($this->getArrayCopy() as $sourceSize) {
116 5
            $mediaCondition = $sourceSize->getMediaCondition();
117
118
            // If the current breakpoint and density matches the source size condition
119 5
            if ($mediaCondition->matches($breakpoint, $density, $lastMinimumWidth)) {
120 5
                return $this->findImageCandidateForSourceSize(
121 5
                    $sourceSize,
122 5
                    $imageCandidates,
123 5
                    $density,
124 5
                    $breakpoint,
125 5
                    $this->getSourceSizeMaximumWidth($mediaCondition, $lastMinimumWidth)
126
                );
127
            }
128 3
            $lastMinimumWidth = $mediaCondition->getMinimumWidth();
129
        }
130
131 1
        return null;
132
    }
133
134
    /**
135
     * Find an image candidate for a particular source size
136
     *
137
     * @param SourceSize $sourceSize                      Matching source size
138
     * @param ImageCandidateSetInterface $imageCandidates Image candidates
139
     * @param float $density                              Density
140
     * @param AbsoluteLengthInterface $minWidth           Minimum viewport width
141
     * @param AbsoluteLengthInterface|null $maxWidth      Maximum viewport width
142
     *
143
     * @return SourceSizeImageCandidateMatch|null
144
     */
145 5
    protected function findImageCandidateForSourceSize(
146
        SourceSize $sourceSize,
147
        ImageCandidateSetInterface $imageCandidates,
148
        float $density,
149
        AbsoluteLengthInterface $minWidth,
150
        AbsoluteLengthInterface $maxWidth = null
151
    ): ?SourceSizeImageCandidateMatch {
152
        // If there's no upper limit: Use the largest image candidate in any case
153 5
        if ($maxWidth === null) {
154 4
            return $this->createLargestImageCandidateMatch($sourceSize, $imageCandidates);
155
        }
156
157
        // Run through all image candidates for the effective minimum image, current source size and current breakpoint
158 4
        return $this->findImageCandidateForMinImageWidth(
159 4
            $sourceSize,
160 4
            $imageCandidates,
161 4
            max($sourceSize->getValue()->getValue($minWidth), $sourceSize->getValue()->getValue($maxWidth)) * $density
0 ignored issues
show
Unused Code introduced by
The call to Jkphl\Respimgcss\Domain\...thInterface::getValue() has too many arguments starting with $minWidth. ( Ignorable by Annotation )

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

161
            max($sourceSize->getValue()->/** @scrutinizer ignore-call */ getValue($minWidth), $sourceSize->getValue()->getValue($maxWidth)) * $density

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
Bug introduced by
max($sourceSize->getValu...($maxWidth)) * $density of type double is incompatible with the type integer expected by parameter $minImageWidth of Jkphl\Respimgcss\Infrast...idateForMinImageWidth(). ( Ignorable by Annotation )

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

161
            /** @scrutinizer ignore-type */ max($sourceSize->getValue()->getValue($minWidth), $sourceSize->getValue()->getValue($maxWidth)) * $density
Loading history...
162
        );
163
    }
164
165
    /**
166
     * Create and return a match for the largest image candidate
167
     *
168
     * @param SourceSize $sourceSize                      Source size
169
     * @param ImageCandidateSetInterface $imageCandidates Image candidates
170
     *
171
     * @return SourceSizeImageCandidateMatch|null Largest image candidate match
172
     */
173 4
    protected function createLargestImageCandidateMatch(
174
        SourceSize $sourceSize,
175
        ImageCandidateSetInterface $imageCandidates
176
    ): ?SourceSizeImageCandidateMatch {
177 4
        if (count($imageCandidates)) {
178 3
            $largestImageCandidate = $imageCandidates[count($imageCandidates) - 1];
179
180 3
            return $this->createImageCandidateMatch($sourceSize, $largestImageCandidate);
181
        }
182
183 1
        return null;
184
    }
185
186
    /**
187
     * Create a source size image candidate match
188
     *
189
     * @param SourceSize $sourceSize                  Matching source size
190
     * @param ImageCandidateInterface $imageCandidate Image candidata
191
     *
192
     * @return SourceSizeImageCandidateMatch Source size image candidate match
193
     */
194 3
    protected function createImageCandidateMatch(
195
        SourceSize $sourceSize,
196
        ImageCandidateInterface $imageCandidate
197
    ): SourceSizeImageCandidateMatch {
198 3
        $mediaCondition = new MediaCondition('', $sourceSize->getMediaCondition()->getValue());
199
200 3
        return new ImageCandidateMatch($mediaCondition, $imageCandidate);
201
    }
202
203
    /**
204
     * Find an image candidate for a particular source size
205
     *
206
     * @param SourceSize $sourceSize                      Matching source size
207
     * @param ImageCandidateSetInterface $imageCandidates Image candidates
208
     * @param int $minImageWidth                          Minimum image width
209
     *
210
     * @return SourceSizeImageCandidateMatch|null Image candidate
211
     */
212 4
    protected function findImageCandidateForMinImageWidth(
213
        SourceSize $sourceSize,
214
        ImageCandidateSetInterface $imageCandidates,
215
        int $minImageWidth
216
    ): ?SourceSizeImageCandidateMatch {
217
        // Run through all image candidates
218
        /** @var ImageCandidateInterface $imageCandidate */
219 4
        foreach ($imageCandidates as $imageCandidate) {
220 4
            if ($imageCandidate->getValue() >= $minImageWidth) {
221 4
                return $this->createImageCandidateMatch($sourceSize, $imageCandidate);
222
            }
223
        }
224
225 1
        return null;
226
    }
227
228
    /**
229
     * Get the maximum width for a source size
230
     *
231
     * @param SourceSizeMediaCondition $condition Source size media condition
232
     * @param float|null $lastMinimumWidth        Last source size minimum width
233
     *
234
     * @return AbsoluteLengthInterface Maximum width
235
     */
236 5
    protected function getSourceSizeMaximumWidth(
237
        SourceSizeMediaCondition $condition,
238
        float $lastMinimumWidth = null
239
    ): ?AbsoluteLengthInterface {
240 5
        $maximumWidth = $this->considerLastMinimumWidth($condition->getMaximumWidth(), $lastMinimumWidth);
241 5
        if ($maximumWidth === null) {
242 4
            return null;
243
        }
244 4
        if ($lastMinimumWidth !== null) {
245 3
            $maximumWidth = max(0, min($maximumWidth, $lastMinimumWidth - 1));
246
        }
247
248 4
        return $this->lengthFactory->createAbsoluteLength($maximumWidth);
249
    }
250
251
    /**
252
     * Consider the last minimum width in case the maximum width is undefined
253
     *
254
     * @param int|null $maximumWidth       Maximum width
255
     * @param float|null $lastMinimumWidth Last minimum width
256
     *
257
     * @return float|null Maximum width
258
     */
259 5
    protected function considerLastMinimumWidth(int $maximumWidth = null, float $lastMinimumWidth = null): ?float
260
    {
261 5
        if (($maximumWidth === null) && ($lastMinimumWidth !== null)) {
262 3
            $maximumWidth = max(0, $lastMinimumWidth - 1);
263
        }
264
265 5
        return $maximumWidth;
266
    }
267
268
    /**
269
     * Compare and sort two source sizes against each other
270
     *
271
     * @param SourceSize $sourceSize1 Source size 1
272
     * @param SourceSize $sourceSize2 Source size 2
273
     *
274
     * @return int Sort order
275
     */
276 4
    protected function sortSourceSizes(SourceSize $sourceSize1, SourceSize $sourceSize2): int
277
    {
278 4
        $hasConditions1 = $sourceSize1->hasConditions();
279 4
        $hasConditions2 = $sourceSize2->hasConditions();
280
281
        // If one of the sources sizes doesn't have conditions: Default source size (move to the end)
282 4
        if ($hasConditions1 !== $hasConditions2) {
283 3
            return $hasConditions1 ? -1 : 1;
284
        }
285
286 4
        return $hasConditions1 ? $this->sortSourceSizesByWidth($sourceSize1, $sourceSize2) : 0;
287
    }
288
289
    /**
290
     * Compare and sort two source sizes by width
291
     *
292
     * @param SourceSize $sourceSize1 Source size 1
293
     * @param SourceSize $sourceSize2 Source size 2
294
     *
295
     * @return int Sort order
296
     */
297 4
    protected function sortSourceSizesByWidth(SourceSize $sourceSize1, SourceSize $sourceSize2): int
298
    {
299
        // Sort by minimum width
300 4
        $minWidth1 = $sourceSize1->getMediaCondition()->getMinimumWidth();
301 4
        $minWidth2 = $sourceSize2->getMediaCondition()->getMinimumWidth();
302 4
        if ($minWidth1 !== $minWidth2) {
303 3
            return $this->sortSourceSizesByDifferingValues($minWidth1, $minWidth2);
304
        }
305
306
        // Sort by maximum width
307 2
        $maxWidth1 = $sourceSize1->getMediaCondition()->getMaximumWidth();
308 2
        $maxWidth2 = $sourceSize2->getMediaCondition()->getMaximumWidth();
309 2
        if ($maxWidth1 !== $maxWidth2) {
310 1
            return $this->sortSourceSizesByDifferingValues($maxWidth1, $maxWidth2);
311
        }
312
313
        // Sort by resolution
314 1
        return $this->sortSourceSizesByResolution($sourceSize1, $sourceSize2);
315
    }
316
317
    /**
318
     * Sort by differing values
319
     *
320
     * @param float|null $value1 Value 1
321
     * @param float|null $value2 Value 2
322
     *
323
     * @return int Sort order
324
     */
325 4
    protected function sortSourceSizesByDifferingValues(float $value1 = null, float $value2 = null): int
326
    {
327 4
        if ($value1 === null) {
328 1
            return -1;
329
        }
330 4
        if ($value2 === null) {
331 1
            return 1;
332
        }
333
334 4
        return ($value1 > $value2) ? -1 : 1;
335
    }
336
337
    /**
338
     * Compare and sort two source sizes by resolution
339
     *
340
     * @param SourceSize $sourceSize1 Source size 1
341
     * @param SourceSize $sourceSize2 Source size 2
342
     *
343
     * @return int Sort order
344
     */
345 1
    protected function sortSourceSizesByResolution(SourceSize $sourceSize1, SourceSize $sourceSize2): int
346
    {
347
        // Sort by minimum resolution
348 1
        $minResolution1 = $sourceSize1->getMediaCondition()->getMinimumResolution();
349 1
        $minResolution2 = $sourceSize2->getMediaCondition()->getMinimumResolution();
350 1
        if ($minResolution1 !== $minResolution2) {
351 1
            return $this->sortSourceSizesByDifferingValues($minResolution1, $minResolution2);
352
        }
353
354
        // Sort by maximum resolution
355 1
        $maxResolution1 = $sourceSize1->getMediaCondition()->getMaximumResolution();
356 1
        $maxResolution2 = $sourceSize2->getMediaCondition()->getMaximumResolution();
357 1
        if ($maxResolution1 !== $maxResolution2) {
358 1
            return $this->sortSourceSizesByDifferingValues($maxResolution1, $maxResolution2);
359
        }
360
361 1
        return 0;
362
    }
363
}
364