Completed
Push — master ( 5b2b8e...821ba7 )
by Joschi
02:04
created

SourceSizeList::findImageCandidate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3.0052

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 3
nop 3
dl 0
loc 23
ccs 11
cts 12
cp 0.9167
crap 3.0052
rs 9.0856
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 5
    public function __construct(array $sourceSizes, LengthFactoryInterface $lengthFactory)
78
    {
79
        // Run through all source sizes
80 5
        foreach ($sourceSizes as $sourceSize) {
81
            // If the source size is invalid
82 4
            if (!($sourceSize instanceof SourceSize)) {
83 1
                throw new InvalidArgumentException(
84 1
                    InvalidArgumentException::INVALID_SOURCE_SIZE_STR,
85 4
                    InvalidArgumentException::INVALID_SOURCE_SIZE
86
                );
87
            }
88
        }
89
90 4
        usort($sourceSizes, [$this, 'sortSourceSizes']);
91 4
        parent::__construct($sourceSizes);
92
93 4
        $this->lengthFactory = $lengthFactory;
94 4
    }
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 1
    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 1
        $lastMinimumWidth = null;
114 1
        foreach ($this->getArrayCopy() as $sourceSize) {
115 1
            $mediaCondition = $sourceSize->getMediaCondition();
116 1
            if ($mediaCondition->matches($breakpoint, $density)) {
117 1
                return $this->findImageCandidateForSourceSize(
118 1
                    $sourceSize,
119 1
                    $imageCandidates,
120 1
                    $breakpoint,
121 1
                    $this->getSourceSizeMaximumWidth($mediaCondition, $lastMinimumWidth)
122
                );
123
            }
124 1
            $lastMinimumWidth = $mediaCondition->getMinimumWidth();
125
        }
126
127
        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 1
    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 anyway
147 1
        if ($maxWidth === null) {
148 1
            return $this->createLargestImageCandidateMatch($sourceSize, $imageCandidates);
149
        }
150
        // Calculate the effective minimum image width for the current source size and breakpoint
151 1
        $minImageWidth = max(
152 1
            $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

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