Passed
Push — master ( e014bc...910d8e )
by Joschi
02:01
created

SourceSizeList::sortSourceSizesByDifferingValues()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 4
nop 2
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 4
rs 9.2
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
 */
60
class SourceSizeList extends \ArrayObject implements SourceSizeListInterface
61
{
62
    /**
63
     * Length factory
64
     *
65
     * @var LengthFactoryInterface
66
     */
67
    protected $lengthFactory;
68
69
    /**
70
     * Source size list constructor
71
     *
72
     * @param SourceSize[] $sourceSizes             Source sizes
73
     * @param LengthFactoryInterface $lengthFactory Length factory
74
     *
75
     * @throws InvalidArgumentException If the source size is invalid
76
     */
77 9
    public function __construct(array $sourceSizes, LengthFactoryInterface $lengthFactory)
78
    {
79
        // Run through all source sizes
80 9
        foreach ($sourceSizes as $sourceSize) {
81
            // If the source size is invalid
82 7
            if (!($sourceSize instanceof SourceSize)) {
83 1
                throw new InvalidArgumentException(
84 1
                    InvalidArgumentException::INVALID_SOURCE_SIZE_STR,
85 7
                    InvalidArgumentException::INVALID_SOURCE_SIZE
86
                );
87
            }
88
        }
89
90 8
        usort($sourceSizes, [$this, 'sortSourceSizes']);
91 8
        parent::__construct($sourceSizes);
92
93 8
        $this->lengthFactory = $lengthFactory;
94 8
    }
95
96
    /**
97
     * Find the optimum image candidate for a particular breakpoint
98
     *
99
     * @param ImageCandidateSetInterface $imageCandidates Image candidates
100
     * @param AbsoluteLengthInterface $breakpoint         Breakpoint
101
     * @param float $density                              Density
102
     *
103
     * @return SourceSizeImageCandidateMatch|null Image candidate match
104
     */
105 4
    public function findImageCandidate(
106
        ImageCandidateSetInterface $imageCandidates,
107
        AbsoluteLengthInterface $breakpoint,
108
        float $density
109
    ): ?SourceSizeImageCandidateMatch {
110
111
        // Run through the source sizes
112
        /** @var SourceSize $sourceSize */
113 4
        $lastMinimumWidth = null;
114 4
        foreach ($this->getArrayCopy() as $sourceSize) {
115 3
            $mediaCondition = $sourceSize->getMediaCondition();
116 3
            if ($mediaCondition->matches($breakpoint, $density)) {
117 3
                return $this->findImageCandidateForSourceSize(
118 3
                    $sourceSize,
119 3
                    $imageCandidates,
120 3
                    $breakpoint,
121 3
                    $this->getSourceSizeMaximumWidth($mediaCondition, $lastMinimumWidth)
122
                );
123
            }
124 1
            $lastMinimumWidth = $mediaCondition->getMinimumWidth();
125
        }
126
127 1
        return null;
128
    }
129
130
    /**
131
     * Find an image candidate for a particular source size
132
     *
133
     * @param SourceSize $sourceSize                      Matching source size
134
     * @param ImageCandidateSetInterface $imageCandidates Image candidates
135
     * @param AbsoluteLengthInterface $minWidth           Minimum viewport width
136
     * @param AbsoluteLengthInterface|null $maxWidth      Maximum viewport width
137
     *
138
     * @return SourceSizeImageCandidateMatch|null
139
     */
140 3
    protected function findImageCandidateForSourceSize(
141
        SourceSize $sourceSize,
142
        ImageCandidateSetInterface $imageCandidates,
143
        AbsoluteLengthInterface $minWidth,
144
        AbsoluteLengthInterface $maxWidth = null
145
    ): ?SourceSizeImageCandidateMatch {
146
        // If there's no upper limit: Use the largest image candidate in any case
147 3
        if ($maxWidth === null) {
148 2
            return $this->createLargestImageCandidateMatch($sourceSize, $imageCandidates);
149
        }
150
151
        // Calculate the effective minimum image width for the current source size and breakpoint
152 2
        $minImageWidth = max(
153 2
            $sourceSize->getValue()->getValue($minWidth),
0 ignored issues
show
Bug introduced by
The method getValue() does not exist on Jkphl\Respimgcss\Applica...act\UnitLengthInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Jkphl\Respimgcss\Application\Model\AbstractLength. Are you sure you never get one of those? ( Ignorable by Annotation )

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

153
            $sourceSize->getValue()->/** @scrutinizer ignore-call */ getValue($minWidth),
Loading history...
154 2
            $sourceSize->getValue()->getValue($maxWidth)
155
        );
156
157
        // Run through all image candidates
158
        /** @var ImageCandidateInterface $imageCandidate */
159 2
        foreach ($imageCandidates as $imageCandidate) {
160 2
            if ($imageCandidate->getValue() >= $minImageWidth) {
161 2
                return $this->createImageCandidateMatch($sourceSize, $imageCandidate);
162
            }
163
        }
164
165 1
        return null;
166
    }
167
168
    /**
169
     * Create and return a match for the largest image candidate
170
     *
171
     * @param SourceSize $sourceSize                      Source size
172
     * @param ImageCandidateSetInterface $imageCandidates Image candidates
173
     *
174
     * @return SourceSizeImageCandidateMatch|null Largest image candidate match
175
     */
176 2
    protected function createLargestImageCandidateMatch(
177
        SourceSize $sourceSize,
178
        ImageCandidateSetInterface $imageCandidates
179
    ): ?SourceSizeImageCandidateMatch {
180 2
        if (count($imageCandidates)) {
181 1
            $largestImageCandidate = $imageCandidates[count($imageCandidates) - 1];
182 1
            return $this->createImageCandidateMatch($sourceSize, $largestImageCandidate);
183
        }
184
185 1
        return null;
186
    }
187
188
    /**
189
     * Create a source size image candidate match
190
     *
191
     * @param SourceSize $sourceSize                  Matching source size
192
     * @param ImageCandidateInterface $imageCandidate Image candidata
193
     *
194
     * @return SourceSizeImageCandidateMatch Source size image candidate match
195
     */
196 1
    protected function createImageCandidateMatch(
197
        SourceSize $sourceSize,
198
        ImageCandidateInterface $imageCandidate
199
    ): SourceSizeImageCandidateMatch {
200 1
        $mediaCondition = new MediaCondition('', $sourceSize->getMediaCondition()->getValue());
201
202 1
        return new ImageCandidateMatch($mediaCondition, $imageCandidate);
203
    }
204
205
    /**
206
     * Get the maximum width for a source size
207
     *
208
     * @param SourceSizeMediaCondition $condition Source size media condition
209
     * @param float|null $lastMinimumWidth        Last source size minimum width
210
     *
211
     * @return AbsoluteLengthInterface Maximum width
212
     */
213 3
    protected function getSourceSizeMaximumWidth(
214
        SourceSizeMediaCondition $condition,
215
        float $lastMinimumWidth = null
216
    ): ?AbsoluteLengthInterface {
217 3
        $maximumWidth = $condition->getMaximumWidth();
218 3
        if (($maximumWidth === null) && ($lastMinimumWidth !== null)) {
219 1
            $maximumWidth = max(0, $lastMinimumWidth - 1);
220
        }
221 3
        if ($maximumWidth === null) {
222 2
            return null;
223
        }
224 2
        if ($lastMinimumWidth !== null) {
225 1
            $maximumWidth = max(0, min($maximumWidth, $lastMinimumWidth - 1));
226
        }
227 2
        return $this->lengthFactory->createAbsoluteLength($maximumWidth);
228
    }
229
230
    /**
231
     * Compare and sort two source sizes against each other
232
     *
233
     * @param SourceSize $sourceSize1 Source size 1
234
     * @param SourceSize $sourceSize2 Source size 2
235
     *
236
     * @return int Sort order
237
     */
238 2
    protected function sortSourceSizes(SourceSize $sourceSize1, SourceSize $sourceSize2): int
239
    {
240 2
        $hasConditions1 = $sourceSize1->hasConditions();
241 2
        $hasConditions2 = $sourceSize2->hasConditions();
242
243
        // If one of the sources sizes doesn't have conditions: Default source size (move to the end)
244 2
        if ($hasConditions1 !== $hasConditions2) {
245 1
            return $hasConditions1 ? -1 : 1;
246
        }
247
248 2
        return $hasConditions1 ? $this->sortSourceSizesByWidth($sourceSize1, $sourceSize2) : 0;
249
    }
250
251
    /**
252
     * Compare and sort two source sizes by width
253
     *
254
     * @param SourceSize $sourceSize1 Source size 1
255
     * @param SourceSize $sourceSize2 Source size 2
256
     *
257
     * @return int Sort order
258
     */
259 2
    protected function sortSourceSizesByWidth(SourceSize $sourceSize1, SourceSize $sourceSize2): int
260
    {
261
        // Sort by minimum width
262 2
        $minWidth1 = $sourceSize1->getMediaCondition()->getMinimumWidth();
263 2
        $minWidth2 = $sourceSize2->getMediaCondition()->getMinimumWidth();
264 2
        if ($minWidth1 !== $minWidth2) {
265 1
            return $this->sortSourceSizesByDifferingValues($minWidth1, $minWidth2);
266
        }
267
268
        // Sort by maximum width
269 2
        $maxWidth1 = $sourceSize1->getMediaCondition()->getMaximumWidth();
270 2
        $maxWidth2 = $sourceSize2->getMediaCondition()->getMaximumWidth();
271 2
        if ($maxWidth1 !== $maxWidth2) {
272 1
            return $this->sortSourceSizesByDifferingValues($maxWidth1, $maxWidth2);
273
        }
274
275
        // Sort by resolution
276 1
        return $this->sortSourceSizesByResolution($sourceSize1, $sourceSize2);
277
    }
278
279
    /**
280
     * Sort by differing values
281
     *
282
     * @param int|null $value1 Value 1
283
     * @param int|null $value2 Value 2
284
     *
285
     * @return int Sort order
286
     */
287 2
    protected function sortSourceSizesByDifferingValues(int $value1 = null, int $value2 = null): int
288
    {
289 2
        if ($value1 === null) {
290 1
            return -1;
291
        }
292 2
        if ($value2 === null) {
293 1
            return 1;
294
        }
295 2
        return ($value1 > $value2) ? -1 : 1;
296
    }
297
298
    /**
299
     * Compare and sort two source sizes by resolution
300
     *
301
     * @param SourceSize $sourceSize1 Source size 1
302
     * @param SourceSize $sourceSize2 Source size 2
303
     *
304
     * @return int Sort order
305
     */
306 1
    protected function sortSourceSizesByResolution(SourceSize $sourceSize1, SourceSize $sourceSize2): int
307
    {
308
        // Sort by minimum resolution
309 1
        $minResolution1 = $sourceSize1->getMediaCondition()->getMinimumResolution();
310 1
        $minResolution2 = $sourceSize2->getMediaCondition()->getMinimumResolution();
311 1
        if ($minResolution1 !== $minResolution2) {
312 1
            return $this->sortSourceSizesByDifferingValues($minResolution1, $minResolution2);
0 ignored issues
show
Bug introduced by
It seems like $minResolution2 can also be of type double; however, parameter $value2 of Jkphl\Respimgcss\Infrast...izesByDifferingValues() does only seem to accept null|integer, maybe add an additional type check? ( Ignorable by Annotation )

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

312
            return $this->sortSourceSizesByDifferingValues($minResolution1, /** @scrutinizer ignore-type */ $minResolution2);
Loading history...
Bug introduced by
It seems like $minResolution1 can also be of type double; however, parameter $value1 of Jkphl\Respimgcss\Infrast...izesByDifferingValues() does only seem to accept null|integer, maybe add an additional type check? ( Ignorable by Annotation )

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

312
            return $this->sortSourceSizesByDifferingValues(/** @scrutinizer ignore-type */ $minResolution1, $minResolution2);
Loading history...
313
        }
314
315
        // Sort by maximum resolution
316 1
        $maxResolution1 = $sourceSize1->getMediaCondition()->getMaximumResolution();
317 1
        $maxResolution2 = $sourceSize2->getMediaCondition()->getMaximumResolution();
318 1
        if ($maxResolution1 !== $maxResolution2) {
319 1
            return $this->sortSourceSizesByDifferingValues($maxResolution1, $maxResolution2);
320
        }
321
322 1
        return 0;
323
    }
324
}