Passed
Push — master ( e7af6a...141cd5 )
by Joschi
02:15
created

SourceSizeFactory::createFromSourceSizeStr()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 10
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
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\Application\Factory
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\Application\Factory;
38
39
use Jkphl\Respimgcss\Application\Contract\UnitLengthInterface;
40
use Jkphl\Respimgcss\Application\Exceptions\InvalidArgumentException;
41
use Jkphl\Respimgcss\Application\Model\SourceSize;
42
use Jkphl\Respimgcss\Application\Model\SourceSizeMediaCondition;
43
use Jkphl\Respimgcss\Domain\Contract\LengthInterface;
44
use Jkphl\Respimgcss\Domain\Model\Css\ResolutionMediaCondition;
45
use Jkphl\Respimgcss\Domain\Model\Css\WidthMediaCondition;
46
47
/**
48
 * Source size factory
49
 *
50
 * @package    Jkphl\Respimgcss
51
 * @subpackage Jkphl\Respimgcss\Application\Factory
52
 */
53
class SourceSizeFactory extends AbstractLengthFactory
54
{
55
    /**
56
     * Create a source size value from a source size string
57
     *
58
     * @param string $sourceSizeStr Source size string
59
     *
60
     * @return SourceSize Source size
61
     */
62 9
    public function createFromSourceSizeStr(string $sourceSizeStr): SourceSize
63
    {
64
        // Determine the source size value
65 9
        $sourceSizeValue = $this->parseSourceSizeValue($sourceSizeStr);
66
67
        // Determine the associated media condition (if any)
68 6
        $mediaCondition = $this->parseMediaCondition($sourceSizeStr);
69
70
        // Return a source size instance
71 6
        return new SourceSize($sourceSizeValue, $mediaCondition);
72
    }
73
74
    /**
75
     * Parse the length component
76
     *
77
     * @param string $sourceSizeStr Source size string
78
     *
79
     * @return UnitLengthInterface AbstractLength component
80
     * @throws InvalidArgumentException If the source size string is ill-formatted
81
     */
82 9
    protected function parseSourceSizeValue(string &$sourceSizeStr): UnitLengthInterface
83
    {
84
        // If the source size string ends with a parenthesis: Try to parse a calc() base length
85 9
        if (substr($sourceSizeStr, -1) === ')') {
86 4
            return $this->parseSourceSizeCalculatedValue($sourceSizeStr);
87
        }
88
89
        // If the source size string is ill-formatted
90 6
        if (!preg_match('/^(.*\s+)?([^\s]+)$/', $sourceSizeStr, $sourceSizeStrMatch)) {
91 1
            throw new InvalidArgumentException(
92 1
                sprintf(InvalidArgumentException::ILL_FORMATTED_SOURCE_SIZE_STRING_STR, $sourceSizeStr),
93 1
                InvalidArgumentException::ILL_FORMATTED_SOURCE_SIZE_STRING
94
            );
95
        }
96
97
        // Post-process the remaining string
98 5
        $sourceSizeStr = trim($sourceSizeStrMatch[1]);
99
100
        // Return the parsed length
101 5
        return (new LengthFactory($this->calculatorServiceFactory, $this->emPixel))
102 5
            ->createLengthFromString($sourceSizeStrMatch[2]);
103
    }
104
105
    /**
106
     * Parse a calc() based length value
107
     *
108
     * @param string $sourceSizeStr Source size string
109
     *
110
     * @return UnitLengthInterface AbstractLength component
111
     * @throws InvalidArgumentException If the source size string is ill-formatted
112
     */
113 4
    protected function parseSourceSizeCalculatedValue(string &$sourceSizeStr): UnitLengthInterface
114
    {
115
        // Reverse-consume the source size string
116 4
        $sourceSizeRev = strrev($sourceSizeStr);
117 4
        $balance       = null;
118 4
        for ($pos = 0; $pos < strlen($sourceSizeStr); ++$pos) {
119 4
            $balance += $this->getCharacterBalance($sourceSizeRev[$pos]);
120 4
            if ($balance === 0) {
121 2
                $length        = (new CalcLengthFactory($this->calculatorServiceFactory, $this->emPixel))
122 2
                    ->createLengthFromString(substr($sourceSizeStr, -($pos + 5)));
123 2
                $sourceSizeStr = trim(substr($sourceSizeStr, 0, -($pos + 5)));
124
125 2
                return $length;
126
            }
127
        }
128
129
        // Else: The source size string is ill-formatted
130 2
        throw new InvalidArgumentException(
131 2
            sprintf(InvalidArgumentException::ILL_FORMATTED_SOURCE_SIZE_STRING_STR, $sourceSizeStr),
132 2
            InvalidArgumentException::ILL_FORMATTED_SOURCE_SIZE_STRING
133
        );
134
    }
135
136
    /**
137
     * Return the balance value for a particular value
138
     *
139
     * @param string $char Character
140
     *
141
     * @return int Balance value
142
     */
143 4
    protected function getCharacterBalance($char): string
144
    {
145 4
        return ($char === '(') ? 1 : (($char === ')') ? -1 : 0);
146
    }
147
148
    /**
149
     * Parse and instantiate a source size media condition
150
     *
151
     * @param string $mediaConditionString
152
     *
153
     * @return SourceSizeMediaCondition|null Source size media condition
154
     * @see https://drafts.csswg.org/mediaqueries-4/#typedef-media-condition
155
     * @see https://developer.mozilla.org/de/docs/Web/CSS/Media_Queries/Using_media_queries#Pseudo-BNF_(for_those_of_you_that_like_that_kind_of_thing)
156
     *
157
     */
158 6
    protected function parseMediaCondition(string $mediaConditionString): ?SourceSizeMediaCondition
159
    {
160 6
        return new SourceSizeMediaCondition(
161 6
            $mediaConditionString,
162 6
            array_merge(
163 6
                $this->parseWidthMediaConditions($mediaConditionString),
164 6
                $this->parseResolutionMediaConditions($mediaConditionString)
165
            )
166
        );
167
    }
168
169
    /**
170
     * Extract width media conditions
171
     *
172
     * @param string $mediaConditionString Media condition string
173
     *
174
     * @return WidthMediaCondition[] Width media conditions
175
     */
176 6
    protected function parseWidthMediaConditions(string $mediaConditionString): array
177
    {
178 6
        $widthMediaConditions = [];
179
180
        // width | min-width | max-width
181
        // device-width | min-device-width | max-device-width
182 6
        preg_match_all(
183 6
            '/((?:min|max)\-)?(?:device\-)?width\s*\:\s*/',
184 6
            $mediaConditionString,
185 6
            $widthConditionMatches,
186 6
            PREG_OFFSET_CAPTURE
187
        );
188
189
        // Run through all width condition matches
190 6
        foreach ($widthConditionMatches[0] as $widthConditionIndex => $widthConditionMatch) {
191
            try {
192 6
                $matchLength              = strlen($widthConditionMatch[0]) + $widthConditionMatch[1];
193 6
                $widthMediaConditionValue = $this->parseWidthMediaConditionValue(
194 6
                    substr($mediaConditionString, $matchLength)
195
                );
196 4
                $widthMediaConditions[]   = new WidthMediaCondition(
197 4
                    $widthMediaConditionValue,
198 4
                    $widthConditionMatches[1][$widthConditionIndex][0]
199
                );
200 2
            } catch (\Exception $e) {
201 6
                continue;
202
            }
203
        }
204
205 6
        return $widthMediaConditions;
206
    }
207
208
    /**
209
     * Parse a width media condition value
210
     *
211
     * @param string $widthMediaConditionStr Width media condition string
212
     *
213
     * @return UnitLengthInterface Width media condition value
214
     */
215 6
    protected function parseWidthMediaConditionValue(string $widthMediaConditionStr): UnitLengthInterface
216
    {
217 6
        $widthMediaConditionValueStr = $this->shiftMediaConditionValue($widthMediaConditionStr);
218
219
        // Try to parse as simple unit length
220
        try {
221 6
            return (new LengthFactory($this->calculatorServiceFactory, $this->emPixel))
222 6
                ->createLengthFromString($widthMediaConditionValueStr);
223 4
        } catch (InvalidArgumentException $e) {
224
            // Skip
225
        }
226
227
        // Try to parse as calc() length
228 4
        return (new CalcLengthFactory($this->calculatorServiceFactory, $this->emPixel))
229 4
            ->createLengthFromString($widthMediaConditionValueStr);
230
    }
231
232
    /**
233
     * Shift a media condition value off the beginning of a media condition string
234
     *
235
     * @param string $mediaConditionValueStr Media condition string
236
     *
237
     * @return string Media condition value string
238
     */
239 6
    protected function shiftMediaConditionValue(string $mediaConditionValueStr): string
240
    {
241 6
        $stringLength = strlen($mediaConditionValueStr);
242 6
        $balance      = 1;
243 6
        for ($char = 0; $char < $stringLength; ++$char) {
244 6
            switch ($mediaConditionValueStr[$char]) {
245 6
                case ')':
246 6
                    --$balance;
247 6
                    break;
248 6
                case '(':
249 3
                    ++$balance;
250 3
                    break;
251
            }
252 6
            if ($balance == 0) {
253 5
                return substr($mediaConditionValueStr, 0, $char);
254
            }
255
        }
256
257 1
        return $mediaConditionValueStr;
258
    }
259
260
    /**
261
     * Extract resolution media conditions
262
     *
263
     * @param string $mediaConditionString Media condition string
264
     *
265
     * @return ResolutionMediaCondition[] Resolution media conditions
266
     */
267 6
    protected function parseResolutionMediaConditions(string $mediaConditionString): array
268
    {
269 6
        $resolutionMediaConditions = [];
270
271
        // resolution | min-resolution | max-resolution
272 6
        preg_match_all(
273 6
            '/((?:min|max)\-)?resolution\s*\:\s*/',
274 6
            $mediaConditionString,
275 6
            $resolutionConditionMatches,
276 6
            PREG_OFFSET_CAPTURE
277
        );
278
279
280
        // Run through all width condition matches
281 6
        foreach ($resolutionConditionMatches[0] as $resolutionConditionIndex => $resolutionConditionMatch) {
282
            try {
283 3
                $matchLength                   = strlen($resolutionConditionMatch[0]) + $resolutionConditionMatch[1];
284 3
                $resolutionMediaConditionValue = $this->parseResolutionMediaConditionValue(
285 3
                    substr($mediaConditionString, $matchLength)
286
                );
287 2
                $resolutionMediaConditions []  = new ResolutionMediaCondition(
288 2
                    $resolutionMediaConditionValue,
289 2
                    $resolutionConditionMatches[1][$resolutionConditionIndex][0]
290
                );
291 2
            } catch (\Exception $e) {
292 3
                continue;
293
            }
294
        }
295
296 6
        return $resolutionMediaConditions;
297
    }
298
299
    /**
300
     * Parse a resolution media condition value
301
     *
302
     * @param string $resolutionMediaConditionStr Resolution media condition string
303
     *
304
     * @return LengthInterface Resolution media condition value
305
     */
306 3
    protected function parseResolutionMediaConditionValue(string $resolutionMediaConditionStr): LengthInterface
307
    {
308 3
        $resolutionMediaConditionValueStr = $this->shiftMediaConditionValue($resolutionMediaConditionStr);
309
310 3
        return $this->createAbsoluteLength($resolutionMediaConditionValueStr);
0 ignored issues
show
Bug introduced by
$resolutionMediaConditionValueStr of type string is incompatible with the type double expected by parameter $value of Jkphl\Respimgcss\Applica...:createAbsoluteLength(). ( Ignorable by Annotation )

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

310
        return $this->createAbsoluteLength(/** @scrutinizer ignore-type */ $resolutionMediaConditionValueStr);
Loading history...
311
    }
312
}