Passed
Push — master ( 2324c3...510281 )
by Joschi
02:37
created

ViewportCalculatorService::handleCalcToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
ccs 4
cts 4
cp 1
crap 2
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
        // In all other cases: Register the previous token (if any)
143 10
        if ($previousToken) {
144 2
            array_push($refinedTokens, $previousToken);
145
        }
146
147
        // If it's a number token: Stash
148 10
        if ($token->getType() == Token::TYPE_NUMBER) {
149 10
            return $token;
150
        }
151
152 9
        array_push($refinedTokens, $token);
153
154 9
        return null;
155
    }
156
157
    /**
158
     * Handle a particular token
159
     *
160
     * The method returns a list of zero or more (possibly refined) tokens to preerve
161
     *
162
     * @param Token[] $refinedTokens    Refined tokens
163
     * @param int $emPixel              EM to pixel ratio
164
     * @param Token $token              Token
165
     * @param Token|null $previousToken Previous token
166
     *
167
     * @return Token|null               Stash token
168
     * @throws InvalidArgumentException If the word token is invalid
169
     */
170 9
    protected function handleWordToken(
171
        array &$refinedTokens,
172
        int $emPixel,
173
        Token $token,
174
        Token $previousToken = null
175
    ): ?Token {
176
        // If it's a calc() function call: Add the previous token and skip the current one
177 9
        if ($token->getValue() == 'calc') {
178 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...
179
        }
180
181
        // If the previous token is a number: Try to generate a unit length
182 8
        if ($previousToken && ($previousToken->getType() == Token::TYPE_NUMBER)) {
183
            try {
184 8
                return $this->createAndHandleUnitLengthToken($refinedTokens, $emPixel, $token, $previousToken);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->createAndHandleUn...$token, $previousToken) targeting Jkphl\Respimgcss\Infrast...HandleUnitLengthToken() 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...
185 1
            } catch (ApplicationInvalidArgumentException $e) {
186
                // Ignore
187
            }
188
        }
189
190
        // Invalid word token
191 1
        throw new InvalidArgumentException(
192 1
            sprintf(InvalidArgumentException::INVALID_WORD_TOKEN_IN_SOURCE_SIZE_VALUE_STR, $token->getValue()),
193 1
            InvalidArgumentException::INVALID_WORD_TOKEN_IN_SOURCE_SIZE_VALUE
194
        );
195
    }
196
197
    /**
198
     * Handle a calc() token
199
     *
200
     * @param array $refinedTokens      Refined tokens
201
     * @param Token|null $previousToken Previous token
202
     *
203
     * @return null
204
     */
205 8
    protected function handleCalcToken(array &$refinedTokens, Token $previousToken = null)
206
    {
207 8
        if ($previousToken) {
208 1
            array_push($refinedTokens, $previousToken);
209
        }
210
211 8
        return null;
212
    }
213
214
    /**
215
     * Create and handle a unit length token
216
     *
217
     * @param Token[] $refinedTokens    Refined tokens
218
     * @param int $emPixel              EM to pixel ratio
219
     * @param Token $token              Token
220
     * @param Token|null $previousToken Previous token
221
     *
222
     * @return null
223
     */
224 8
    protected function createAndHandleUnitLengthToken(
225
        array &$refinedTokens,
226
        int $emPixel,
227
        Token $token,
228
        Token $previousToken = null
229
    ) {
230 8
        return $this->handleUnitLengthToken(
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->handleUnitLengthT... . $token->getValue())) targeting Jkphl\Respimgcss\Infrast...handleUnitLengthToken() 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...
231 8
            $refinedTokens,
232 8
            (new LengthFactory(new ViewportCalculatorServiceFactory(), $emPixel))
233 8
                ->createLengthFromString($previousToken->getValue().$token->getValue())
0 ignored issues
show
Bug introduced by
The method getValue() does not exist on null. ( Ignorable by Annotation )

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

233
                ->createLengthFromString($previousToken->/** @scrutinizer ignore-call */ getValue().$token->getValue())

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
234
        );
235
    }
236
237
    /**
238
     * Handle a unit length token
239
     *
240
     * @param Token[] $refinedTokens          Refined tokens
241
     * @param UnitLengthInterface $unitLength Unit length
242
     *
243
     * @return null
244
     */
245 7
    protected function handleUnitLengthToken(
246
        array &$refinedTokens,
247
        UnitLengthInterface $unitLength
248
    ) {
249
        // If it's an absolute value
250 7
        if ($unitLength instanceof AbsoluteLength) {
251 7
            array_push($refinedTokens, new Token(strval($unitLength->getValue()), Token::TYPE_NUMBER, 0));
252
253 7
            return null;
254
        }
255
256
        // Else: Substitute with multiplied function expression
257 4
        array_push(
258 4
            $refinedTokens,
259 4
            new Token('(', Token::TYPE_CHARACTER, 0),
260 4
            new Token(strval($unitLength->getOriginalValue() / 100), Token::TYPE_NUMBER, 0),
261 4
            new Token('*', Token::TYPE_CHARACTER, 0),
262 4
            new Token('viewport', Token::TYPE_WORD, 0),
263 4
            new Token('(', Token::TYPE_CHARACTER, 0),
264 4
            new Token(')', Token::TYPE_CHARACTER, 0),
265 4
            new Token(')', Token::TYPE_CHARACTER, 0)
266
        );
267
268 4
        return null;
269
    }
270
271
    /**
272
     * Test whether a calculation token is a viewport token
273
     *
274
     * @param mixed $token Calculation token
275
     *
276
     * @return bool Is viewport token
277
     */
278 7
    public function isViewportToken($token): bool
279
    {
280 7
        return ($token instanceof Token)
281 7
               && ($token->getType() == Token::TYPE_WORD)
282 7
               && ($token->getValue() === 'viewport');
283
    }
284
}