Passed
Push — master ( 510281...1ca4f4 )
by Joschi
02:37
created

ViewportCalculatorService::handleSimpleToken()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 4
nop 3
dl 0
loc 18
ccs 7
cts 7
cp 1
crap 3
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\Model
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 ChrisKonnertz\StringCalc\Container\ContainerInterface;
40
use ChrisKonnertz\StringCalc\StringCalc;
41
use ChrisKonnertz\StringCalc\Tokenizer\Token;
42
use Jkphl\Respimgcss\Application\Contract\CalculatorServiceInterface;
43
use Jkphl\Respimgcss\Application\Contract\UnitLengthInterface;
44
use Jkphl\Respimgcss\Application\Exceptions\InvalidArgumentException as ApplicationInvalidArgumentException;
45
use Jkphl\Respimgcss\Application\Factory\LengthFactory;
46
use Jkphl\Respimgcss\Application\Model\AbsoluteLength;
47
use Jkphl\Respimgcss\Domain\Contract\AbsoluteLengthInterface;
48
use Jkphl\Respimgcss\Ports\InvalidArgumentException;
49
50
/**
51
 * Custom string calculator
52
 *
53
 * @package    Jkphl\Respimgcss
54
 * @subpackage Jkphl\Respimgcss\Application\Model
55
 */
56
class ViewportCalculatorService extends StringCalc implements CalculatorServiceInterface
57
{
58
    /**
59
     * Custom string calculator constructor
60
     *
61
     * @param AbsoluteLengthInterface $viewport Viewport width
62
     * @param ContainerInterface $container     Container
63
     *
64
     * @throws \ChrisKonnertz\StringCalc\Exceptions\ContainerException
65
     * @throws \ChrisKonnertz\StringCalc\Exceptions\InvalidIdentifierException
66
     * @throws \ChrisKonnertz\StringCalc\Exceptions\NotFoundException
67
     */
68 16
    public function __construct(AbsoluteLengthInterface $viewport = null)
69
    {
70 16
        parent::__construct();
71 16
        $stringHelper     = $this->getContainer()->get('stringcalc_stringhelper');
72 16
        $viewportFunction = new ViewportFunction(
73 16
            $stringHelper,
74 16
            $viewport ?: (new LengthFactory(new ViewportCalculatorServiceFactory(), 16))->createAbsoluteLength(0)
75
        );
76 16
        $this->symbolContainer->add($viewportFunction);
77 16
    }
78
79
    /**
80
     * Evaluate calculation tokens
81
     *
82
     * @param Token[] $tokens Calculation tokens
83
     *
84
     * @return float Result
85
     * @throws \ChrisKonnertz\StringCalc\Exceptions\ContainerException
86
     * @throws \ChrisKonnertz\StringCalc\Exceptions\NotFoundException
87
     */
88 6
    public function evaluate(array $tokens): float
89
    {
90 6
        $calculationRootNode = $this->parse($tokens);
91
92 5
        return $this->container->get('stringcalc_calculator')->calculate($calculationRootNode);
93
    }
94
95
    /**
96
     * Refine a list of calculation tokens
97
     *
98
     * @param array $tokens Calculation tokens
99
     * @param int $emPixel  EM to pixel ratio
100
     *
101
     * @return array Refined Calculation tokens
102
     */
103 10
    public function refineCalculationTokens(array $tokens, int $emPixel): array
104
    {
105 10
        $refinedTokens = [];
106 10
        $previousToken = null;
107
108
        // Run through all tokens
109 10
        foreach ($tokens as $token) {
110 10
            $previousToken = $this->handleToken($refinedTokens, $emPixel, $token, $previousToken);
111
        }
112
113
        // Add the last token
114 9
        if ($previousToken) {
115 1
            array_push($refinedTokens, $previousToken);
116
        }
117
118 9
        return $refinedTokens;
119
    }
120
121
    /**
122
     * Handle a particular token
123
     *
124
     * @param Token[] $refinedTokens    Refined tokens
125
     * @param int $emPixel              EM to pixel ratio
126
     * @param Token $token              Token
127
     * @param Token|null $previousToken Previous token
128
     *
129
     * @return Token|null               Stash token
130
     */
131 10
    protected function handleToken(
132
        array &$refinedTokens,
133
        int $emPixel,
134
        Token $token,
135
        Token $previousToken = null
136
    ): ?Token {
137
        // If it's a word token: Handle individually
138 10
        if ($token->getType() == Token::TYPE_WORD) {
139 9
            return $this->handleWordToken($refinedTokens, $emPixel, $token, $previousToken);
140
        }
141
142
        // Handle as simple token
143 10
        return $this->handleSimpleToken($refinedTokens, $token, $previousToken);
144
    }
145
146
    /**
147
     * Handle a simple token
148
     *
149
     * @param Token[] $refinedTokens    Refined tokens
150
     * @param Token $token              Token
151
     * @param Token|null $previousToken Previous token
152
     *
153
     * @return Token|null               Stash token
154
     */
155 10
    protected function handleSimpleToken(
156
        array &$refinedTokens,
157
        Token $token,
158
        Token $previousToken = null
159
    ): ?Token {
160
        // In all other cases: Register the previous token (if any)
161 10
        if ($previousToken) {
162 2
            array_push($refinedTokens, $previousToken);
163
        }
164
165
        // If it's a number token: Stash
166 10
        if ($token->getType() == Token::TYPE_NUMBER) {
167 10
            return $token;
168
        }
169
170 9
        array_push($refinedTokens, $token);
171
172 9
        return null;
173
    }
174
175
    /**
176
     * Handle a particular token
177
     *
178
     * The method returns a list of zero or more (possibly refined) tokens to preerve
179
     *
180
     * @param Token[] $refinedTokens    Refined tokens
181
     * @param int $emPixel              EM to pixel ratio
182
     * @param Token $token              Token
183
     * @param Token|null $previousToken Previous token
184
     *
185
     * @return Token|null               Stash token
186
     * @throws InvalidArgumentException If the word token is invalid
187
     */
188 9
    protected function handleWordToken(
189
        array &$refinedTokens,
190
        int $emPixel,
191
        Token $token,
192
        Token $previousToken = null
193
    ): ?Token {
194
        // If it's a calc() function call: Add the previous token and skip the current one
195 9
        if ($token->getValue() == 'calc') {
196 8
            return $this->handleCalcToken($refinedTokens, $previousToken);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->handleCalcToken($...Tokens, $previousToken) targeting Jkphl\Respimgcss\Infrast...vice::handleCalcToken() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

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

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

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

Loading history...
197
        }
198
199
        // If the previous token is a number: Try to generate a unit length
200 8
        if ($previousToken && ($previousToken->getType() == Token::TYPE_NUMBER)) {
201
            try {
202 8
                $this->createAndHandleUnitLengthToken($refinedTokens, $emPixel, $token, $previousToken);
203
204 7
                return null;
205 1
            } catch (ApplicationInvalidArgumentException $e) {
206
                // Ignore
207
            }
208
        }
209
210
        // Invalid word token
211 1
        throw new InvalidArgumentException(
212 1
            sprintf(InvalidArgumentException::INVALID_WORD_TOKEN_IN_SOURCE_SIZE_VALUE_STR, $token->getValue()),
213 1
            InvalidArgumentException::INVALID_WORD_TOKEN_IN_SOURCE_SIZE_VALUE
214
        );
215
    }
216
217
    /**
218
     * Handle a calc() token
219
     *
220
     * @param array $refinedTokens      Refined tokens
221
     * @param Token|null $previousToken Previous token
222
     *
223
     * @return null
224
     */
225 8
    protected function handleCalcToken(array &$refinedTokens, Token $previousToken = null)
226
    {
227 8
        if ($previousToken) {
228 1
            array_push($refinedTokens, $previousToken);
229
        }
230
231 8
        return null;
232
    }
233
234
    /**
235
     * Create and handle a unit length token
236
     *
237
     * @param Token[] $refinedTokens Refined tokens
238
     * @param int $emPixel           EM to pixel ratio
239
     * @param Token $token           Token
240
     * @param Token $previousToken   Previous token
241
     */
242 8
    protected function createAndHandleUnitLengthToken(
243
        array &$refinedTokens,
244
        int $emPixel,
245
        Token $token,
246
        Token $previousToken
247
    ): void {
248 8
        $unitLength = (new LengthFactory(new ViewportCalculatorServiceFactory(), $emPixel))
249 8
            ->createLengthFromString($previousToken->getValue().$token->getValue());
250
251
        // If it's an absolute value
252 7
        if ($unitLength instanceof AbsoluteLength) {
253 7
            array_push($refinedTokens, new Token(strval($unitLength->getValue()), Token::TYPE_NUMBER, 0));
0 ignored issues
show
Bug introduced by
The call to Jkphl\Respimgcss\Applica...wportLength::getValue() has too few arguments starting with viewport. ( Ignorable by Annotation )

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

253
            array_push($refinedTokens, new Token(strval($unitLength->/** @scrutinizer ignore-call */ getValue()), Token::TYPE_NUMBER, 0));

This check compares calls to functions or methods with their respective definitions. If the call has less 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...
Bug introduced by
The call to Jkphl\Respimgcss\Applica...ntageLength::getValue() has too few arguments starting with viewport. ( Ignorable by Annotation )

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

253
            array_push($refinedTokens, new Token(strval($unitLength->/** @scrutinizer ignore-call */ getValue()), Token::TYPE_NUMBER, 0));

This check compares calls to functions or methods with their respective definitions. If the call has less 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...
254
255 7
            return;
256
        }
257
258 4
        $this->handleUnitLengthToken($refinedTokens, $unitLength);
259 4
    }
260
261
    /**
262
     * Handle a unit length token
263
     *
264
     * @param Token[] $refinedTokens          Refined tokens
265
     * @param UnitLengthInterface $unitLength Unit length
266
     */
267 4
    protected function handleUnitLengthToken(
268
        array &$refinedTokens,
269
        UnitLengthInterface $unitLength
270
    ): void {
271 4
        array_push(
272 4
            $refinedTokens,
273 4
            new Token('(', Token::TYPE_CHARACTER, 0),
274 4
            new Token(strval($unitLength->getOriginalValue() / 100), Token::TYPE_NUMBER, 0),
275 4
            new Token('*', Token::TYPE_CHARACTER, 0),
276 4
            new Token('viewport', Token::TYPE_WORD, 0),
277 4
            new Token('(', Token::TYPE_CHARACTER, 0),
278 4
            new Token(')', Token::TYPE_CHARACTER, 0),
279 4
            new Token(')', Token::TYPE_CHARACTER, 0)
280
        );
281 4
    }
282
283
    /**
284
     * Test whether a calculation token is a viewport token
285
     *
286
     * @param mixed $token Calculation token
287
     *
288
     * @return bool Is viewport token
289
     */
290 7
    public function isViewportToken($token): bool
291
    {
292 7
        return ($token instanceof Token)
293 7
               && ($token->getType() == Token::TYPE_WORD)
294 7
               && ($token->getValue() === 'viewport');
295
    }
296
}