Passed
Push — master ( 81dcb1...8dba8b )
by Joschi
02:35
created

SourceSizeFactory::parseMediaCondition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
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 Sabberworm\CSS\Parser;
42
43
/**
44
 * Source size factory
45
 *
46
 * @package    Jkphl\Respimgcss
47
 * @subpackage Jkphl\Respimgcss\Application\Factory
48
 */
49
class SourceSizeFactory extends AbstractLengthFactory
50
{
51
    /**
52
     * Create a source size value from a source size string
53
     *
54
     * @param string $sourceSizeStr Source size string
55
     *
56
     * @return UnitLengthInterface Source size value
57
     * @throws \ChrisKonnertz\StringCalc\Exceptions\ContainerException
58
     * @throws \ChrisKonnertz\StringCalc\Exceptions\InvalidIdentifierException
59
     * @throws \ChrisKonnertz\StringCalc\Exceptions\NotFoundException
60
     */
61 1
    public function createFromSourceSizeStr(string $sourceSizeStr)
62
    {
63
        // Determine the source size value
64 1
        $sourceSizeValue = $this->parseSourceSizeValue($sourceSizeStr);
65
66
        // Determine the associated media condition (if any)
67 1
        $mediaCondition = $this->parseMediaCondition($sourceSizeStr);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $mediaCondition is correct as $this->parseMediaCondition($sourceSizeStr) targeting Jkphl\Respimgcss\Applica...::parseMediaCondition() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Unused Code introduced by
The assignment to $mediaCondition is dead and can be removed.
Loading history...
68
69
70 1
        return $sourceSizeValue;
71
    }
72
73
    /**
74
     * Parse the length component
75
     *
76
     * @param string $sourceSizeStr Source size string
77
     *
78
     * @return UnitLengthInterface AbstractLength component
79
     * @throws InvalidArgumentException If the source size string is ill-formatted
80
     * @throws \ChrisKonnertz\StringCalc\Exceptions\ContainerException
81
     * @throws \ChrisKonnertz\StringCalc\Exceptions\InvalidIdentifierException
82
     * @throws \ChrisKonnertz\StringCalc\Exceptions\NotFoundException
83
     */
84 1
    protected function parseSourceSizeValue(string &$sourceSizeStr): UnitLengthInterface
85
    {
86
        // If the source size string ends with a parenthesis: Try to parse a calc() base length
87 1
        if (substr($sourceSizeStr, -1) === ')') {
88 1
            return $this->parseSourceSizeCalculatedValue($sourceSizeStr);
89
        }
90
91
        // If the source size string is ill-formatted
92 1
        if (!preg_match('/^(.*\s+)?([^\s]+)$/', $sourceSizeStr, $sourceSizeStrMatch)) {
93
            throw new InvalidArgumentException(
94
                sprintf(InvalidArgumentException::ILL_FORMATTED_SOURCE_SIZE_STRING_STR, $sourceSizeStr),
95
                InvalidArgumentException::ILL_FORMATTED_SOURCE_SIZE_STRING
96
            );
97
        }
98
99
        // Post-process the remaining string
100 1
        $sourceSizeStr = trim($sourceSizeStrMatch[1]);
101
102
        // Return the parsed length
103 1
        return (new LengthFactory($this->emPixel))->createLengthFromString($sourceSizeStrMatch[2], $this->emPixel);
0 ignored issues
show
Unused Code introduced by
The call to Jkphl\Respimgcss\Applica...reateLengthFromString() has too many arguments starting with $this->emPixel. ( Ignorable by Annotation )

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

103
        return (new LengthFactory($this->emPixel))->/** @scrutinizer ignore-call */ createLengthFromString($sourceSizeStrMatch[2], $this->emPixel);

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...
104
    }
105
106
    /**
107
     * Parse a calc() based length value
108
     *
109
     * @param string $sourceSizeStr Source size string
110
     *
111
     * @return UnitLengthInterface AbstractLength component
112
     * @throws InvalidArgumentException If the source size string is ill-formatted
113
     * @throws \ChrisKonnertz\StringCalc\Exceptions\ContainerException
114
     * @throws \ChrisKonnertz\StringCalc\Exceptions\InvalidIdentifierException
115
     * @throws \ChrisKonnertz\StringCalc\Exceptions\NotFoundException
116
     */
117 1
    protected function parseSourceSizeCalculatedValue(string &$sourceSizeStr): UnitLengthInterface
118
    {
119
        // Reverse-consume the source size string
120 1
        $sourceSizeRev = strrev($sourceSizeStr);
121 1
        $balance       = null;
122 1
        for ($pos = 0; $pos < strlen($sourceSizeStr); ++$pos) {
123 1
            $balance += $this->getCharacterBalance($sourceSizeRev[$pos]);
124 1
            if ($balance === 0) {
125 1
                $length        = (new CalcLengthFactory($this->emPixel))->createFromString(
126 1
                    substr($sourceSizeStr, -($pos + 5))
127
                );
128 1
                $sourceSizeStr = trim(substr($sourceSizeStr, 0, -($pos + 5)));
129
130 1
                return $length;
131
            }
132
        }
133
134
        // Else: The source size string is ill-formatted
135
        throw new InvalidArgumentException(
136
            sprintf(InvalidArgumentException::ILL_FORMATTED_SOURCE_SIZE_STRING_STR, $sourceSizeStr),
137
            InvalidArgumentException::ILL_FORMATTED_SOURCE_SIZE_STRING
138
        );
139
    }
140
141
    /**
142
     * Return the balance value for a particular value
143
     *
144
     * @param string $char Character
145
     *
146
     * @return int Balance value
147
     */
148 1
    protected function getCharacterBalance($char): string
149
    {
150 1
        return ($char === ')') ? 1 : (($char === '(') ? -1 : 0);
151
    }
152
153
154
    /**
155
     * @param string $mediaConditionString
156
     * @see https://drafts.csswg.org/mediaqueries-4/#typedef-media-condition
157
     * @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)
158
     */
159 1
    protected function parseMediaCondition(string $mediaConditionString)
0 ignored issues
show
Unused Code introduced by
The parameter $mediaConditionString is not used and could be removed. ( Ignorable by Annotation )

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

159
    protected function parseMediaCondition(/** @scrutinizer ignore-unused */ string $mediaConditionString)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
160
    {
161 1
        $parser = new Parser('@media screen and (min-width: 10em) {div{display: block}}');
162 1
        print_r($parser->parse());
163
        // width | min-width | max-width
164
        // device-width | min-device-width | max-device-width
165
        // resolution | min-resolution | max-resolution
166
    }
167
}