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

ViewportCalculatorService::handleUnitLengthToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 12
nc 2
nop 2
dl 0
loc 21
ccs 13
cts 13
cp 1
crap 2
rs 9.3142
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\Factory\LengthFactory;
45
use Jkphl\Respimgcss\Application\Model\AbsoluteLength;
46
use Jkphl\Respimgcss\Domain\Contract\AbsoluteLengthInterface;
47
use Jkphl\Respimgcss\Ports\InvalidArgumentException;
48
49
/**
50
 * Custom string calculator
51
 *
52
 * @package    Jkphl\Respimgcss
53
 * @subpackage Jkphl\Respimgcss\Application\Model
54
 */
55
class ViewportCalculatorService extends StringCalc implements CalculatorServiceInterface
56
{
57
    /**
58
     * Custom string calculator constructor
59
     *
60
     * @param AbsoluteLengthInterface $viewport Viewport width
61
     * @param ContainerInterface $container     Container
62
     *
63
     * @throws \ChrisKonnertz\StringCalc\Exceptions\ContainerException
64
     * @throws \ChrisKonnertz\StringCalc\Exceptions\InvalidIdentifierException
65
     * @throws \ChrisKonnertz\StringCalc\Exceptions\NotFoundException
66
     */
67 9
    public function __construct(AbsoluteLengthInterface $viewport = null)
68
    {
69 9
        parent::__construct();
70 9
        $stringHelper     = $this->getContainer()->get('stringcalc_stringhelper');
71 9
        $viewportFunction = new ViewportFunction(
72 9
            $stringHelper,
73 9
            $viewport ?: (new LengthFactory(new ViewportCalculatorServiceFactory(), 16))->createAbsoluteLength(0)
74
        );
75 9
        $this->symbolContainer->add($viewportFunction);
76 9
    }
77
78
    /**
79
     * Evaluate calculation tokens
80
     *
81
     * @param Token[] $tokens Calculation tokens
82
     *
83
     * @return float Result
84
     * @throws \ChrisKonnertz\StringCalc\Exceptions\ContainerException
85
     * @throws \ChrisKonnertz\StringCalc\Exceptions\NotFoundException
86
     */
87 6
    public function evaluate(array $tokens): float
88
    {
89 6
        $calculationRootNode = $this->parse($tokens);
90
91 5
        return $this->container->get('stringcalc_calculator')->calculate($calculationRootNode);
92
    }
93
94
    /**
95
     * Refine a list of calculation tokens
96
     *
97
     * @param array $tokens Calculation tokens
98
     * @param int $emPixel  EM to pixel ratio
99
     *
100
     * @return array Refined Calculation tokens
101
     */
102 7
    public function refineCalculationTokens(array $tokens, int $emPixel): array
103
    {
104 7
        $refinedTokens = [];
105 7
        $previousToken = null;
106
107
        // Run through all tokens
108 7
        foreach ($tokens as $token) {
109 7
            $previousToken = $this->handleToken($refinedTokens, $emPixel, $token, $previousToken);
110
        }
111
112
        // Add the last token
113 7
        if ($previousToken) {
114
            array_push($refinedTokens, $previousToken);
115
        }
116
117 7
        return $refinedTokens;
118
    }
119
120
    /**
121
     * Handle a particular token
122
     *
123
     * @param Token[] $refinedTokens    Refined tokens
124
     * @param int $emPixel              EM to pixel ratio
125
     * @param Token $token              Token
126
     * @param Token|null $previousToken Previous token
127
     *
128
     * @return Token|null               Stash token
129
     */
130 7
    protected function handleToken(
131
        array &$refinedTokens,
132
        int $emPixel,
133
        Token $token,
134
        Token $previousToken = null
135
    ): ?Token {
136
        // If it's a word token: Handle individually
137 7
        if ($token->getType() == Token::TYPE_WORD) {
138 7
            return $this->handleWordToken($refinedTokens, $emPixel, $token, $previousToken);
139
        }
140
141
        // In all other cases: Register the previou token (if any)
142 7
        if ($previousToken) {
143
            array_push($refinedTokens, $previousToken);
144
        }
145
146
        // If it's a number token: Stash
147 7
        if ($token->getType() == Token::TYPE_NUMBER) {
148 7
            return $token;
149
        }
150
151 7
        array_push($refinedTokens, $token);
152
153 7
        return null;
154
    }
155
156
    /**
157
     * Handle a particular token
158
     *
159
     * The method returns a list of zero or more (possibly refined) tokens to preerve
160
     *
161
     * @param Token[] $refinedTokens    Refined tokens
162
     * @param int $emPixel              EM to pixel ratio
163
     * @param Token $token              Token
164
     * @param Token|null $previousToken Previous token
165
     *
166
     * @return Token|null               Stash token
167
     * @throws InvalidArgumentException If the word token is invalid
168
     */
169 7
    protected function handleWordToken(
170
        array &$refinedTokens,
171
        int $emPixel,
172
        Token $token,
173
        Token $previousToken = null
174
    ): ?Token {
175
        // If it's a calc() function call: Add the previous token and skip the current one
176 7
        if ($token->getValue() == 'calc') {
177 7
            if ($previousToken) {
178
                array_push($refinedTokens, $previousToken);
179
            }
180
181 7
            return null;
182
        }
183
184
        // If the previous token is a number: Try to generate a unit length
185 7
        if ($previousToken && ($previousToken->getType() == Token::TYPE_NUMBER)) {
186
            try {
187 7
                $this->handleUnitLengthToken(
188 7
                    $refinedTokens,
189 7
                    (new LengthFactory(new ViewportCalculatorServiceFactory(), $emPixel))
190 7
                        ->createLengthFromString($previousToken->getValue().$token->getValue())
191
                );
192
193 7
                return null;
194
            } catch (InvalidArgumentException $e) {
195
                // Ignore
196
            }
197
        }
198
199
        // Invalid word token
200
        throw new InvalidArgumentException(
201
            sprintf(InvalidArgumentException::INVALID_WORD_TOKEN_IN_SOURCE_SIZE_VALUE_STR, $token->getValue()),
202
            InvalidArgumentException::INVALID_WORD_TOKEN_IN_SOURCE_SIZE_VALUE
203
        );
204
    }
205
206
    /**
207
     * Handle a unit length token
208
     *
209
     * @param Token[] $refinedTokens          Refined tokens
210
     * @param UnitLengthInterface $unitLength Unit length
211
     */
212 7
    protected function handleUnitLengthToken(
213
        array &$refinedTokens,
214
        UnitLengthInterface $unitLength
215
    ): void {
216
        // If it's an absolute value
217 7
        if ($unitLength instanceof AbsoluteLength) {
218 7
            array_push($refinedTokens, new Token(strval($unitLength->getValue()), Token::TYPE_NUMBER, 0));
219
220 7
            return;
221
        }
222
223
        // Else: Substitute with multiplied function expression
224 4
        array_push(
225 4
            $refinedTokens,
226 4
            new Token('(', Token::TYPE_CHARACTER, 0),
227 4
            new Token(strval($unitLength->getOriginalValue() / 100), Token::TYPE_NUMBER, 0),
228 4
            new Token('*', Token::TYPE_CHARACTER, 0),
229 4
            new Token('viewport', Token::TYPE_WORD, 0),
230 4
            new Token('(', Token::TYPE_CHARACTER, 0),
231 4
            new Token(')', Token::TYPE_CHARACTER, 0),
232 4
            new Token(')', Token::TYPE_CHARACTER, 0)
233
        );
234 4
    }
235
236
    /**
237
     * Test whether a calculation token is a viewport token
238
     *
239
     * @param mixed $token Calculation token
240
     *
241
     * @return bool Is viewport token
242
     */
243 7
    public function isViewportToken($token): bool
244
    {
245 7
        return ($token instanceof Token)
246 7
               && ($token->getType() == Token::TYPE_WORD)
247 7
               && ($token->getValue() === 'viewport');
248
    }
249
}