Completed
Push — master ( 8dba8b...0e65c8 )
by Joschi
03:50
created

SourceSizeFactory::shiftMediaConditionValue()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5.009

Importance

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

321
        return $this->createAbsoluteLength(/** @scrutinizer ignore-type */ $resolutionMediaConditionValueStr);
Loading history...
322
    }
323
}