Passed
Push — master ( 6fb159...2324c3 )
by Joschi
01:58
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\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
            if ($previousToken) {
179 1
                array_push($refinedTokens, $previousToken);
180
            }
181
182 8
            return null;
183
        }
184
185
        // If the previous token is a number: Try to generate a unit length
186 8
        if ($previousToken && ($previousToken->getType() == Token::TYPE_NUMBER)) {
187
            try {
188 8
                $this->handleUnitLengthToken(
189 8
                    $refinedTokens,
190 8
                    (new LengthFactory(new ViewportCalculatorServiceFactory(), $emPixel))
191 8
                        ->createLengthFromString($previousToken->getValue().$token->getValue())
192
                );
193
194 7
                return null;
195 1
            } catch (ApplicationInvalidArgumentException $e) {
196
                // Ignore
197
            }
198
        }
199
200
        // Invalid word token
201 1
        throw new InvalidArgumentException(
202 1
            sprintf(InvalidArgumentException::INVALID_WORD_TOKEN_IN_SOURCE_SIZE_VALUE_STR, $token->getValue()),
203 1
            InvalidArgumentException::INVALID_WORD_TOKEN_IN_SOURCE_SIZE_VALUE
204
        );
205
    }
206
207
    /**
208
     * Handle a unit length token
209
     *
210
     * @param Token[] $refinedTokens          Refined tokens
211
     * @param UnitLengthInterface $unitLength Unit length
212
     */
213 7
    protected function handleUnitLengthToken(
214
        array &$refinedTokens,
215
        UnitLengthInterface $unitLength
216
    ): void {
217
        // If it's an absolute value
218 7
        if ($unitLength instanceof AbsoluteLength) {
219 7
            array_push($refinedTokens, new Token(strval($unitLength->getValue()), Token::TYPE_NUMBER, 0));
220
221 7
            return;
222
        }
223
224
        // Else: Substitute with multiplied function expression
225 4
        array_push(
226 4
            $refinedTokens,
227 4
            new Token('(', Token::TYPE_CHARACTER, 0),
228 4
            new Token(strval($unitLength->getOriginalValue() / 100), Token::TYPE_NUMBER, 0),
229 4
            new Token('*', Token::TYPE_CHARACTER, 0),
230 4
            new Token('viewport', Token::TYPE_WORD, 0),
231 4
            new Token('(', Token::TYPE_CHARACTER, 0),
232 4
            new Token(')', Token::TYPE_CHARACTER, 0),
233 4
            new Token(')', Token::TYPE_CHARACTER, 0)
234
        );
235 4
    }
236
237
    /**
238
     * Test whether a calculation token is a viewport token
239
     *
240
     * @param mixed $token Calculation token
241
     *
242
     * @return bool Is viewport token
243
     */
244 7
    public function isViewportToken($token): bool
245
    {
246 7
        return ($token instanceof Token)
247 7
               && ($token->getType() == Token::TYPE_WORD)
248 7
               && ($token->getValue() === 'viewport');
249
    }
250
}