Passed
Pull Request — master (#176)
by Wilmer
05:04 queued 01:09
created

SqlToken::tokensMatch()   C

Complexity

Conditions 16
Paths 12

Size

Total Lines 61
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 16.0116

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 61
ccs 27
cts 28
cp 0.9643
rs 5.5666
c 0
b 0
f 0
cc 16
nc 12
nop 5
crap 16.0116

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Sqlite;
6
7
use ArrayAccess;
8
use Stringable;
9
10
use function array_splice;
11
use function count;
12
use function end;
13
use function in_array;
14
use function mb_substr;
15
use function reset;
16
17
/**
18
 * SqlToken represents SQL tokens produced by {@see SqlTokenizer} or its child classes.
19
 *
20
 * @property SqlToken[] $children Child tokens.
21
 * @property bool $hasChildren Whether the token has children. This property is read-only.
22
 * @property bool $isCollection Whether the token represents a collection of tokens. This property is
23
 * read-only.
24
 * @property string $sql SQL code. This property is read-only.
25
 */
26
final class SqlToken implements ArrayAccess, Stringable
27
{
28
    public const TYPE_CODE = 0;
29
    public const TYPE_STATEMENT = 1;
30
    public const TYPE_TOKEN = 2;
31
    public const TYPE_PARENTHESIS = 3;
32
    public const TYPE_KEYWORD = 4;
33
    public const TYPE_OPERATOR = 5;
34
    public const TYPE_IDENTIFIER = 6;
35
    public const TYPE_STRING_LITERAL = 7;
36
    private int $type = self::TYPE_TOKEN;
37
    private string|null $content = null;
38
    private int|null $startOffset = null;
39
    private int|null $endOffset = null;
40
    private SqlToken|null $parent = null;
41
    private array $children = [];
42
43
    /**
44
     * Returns the SQL code representing the token.
45
     *
46
     * @return string SQL code.
47
     */
48 4
    public function __toString(): string
49
    {
50 4
        return $this->getSql();
51
    }
52
53
    /**
54
     * Returns whether there is a child token at the specified offset.
55
     *
56
     * This method is required by the SPL {@see ArrayAccess} interface. It is implicitly called when you use something
57
     * like `isset($token[$offset])`.
58
     *
59
     * @param int $offset child token offset.
60
     *
61
     * @return bool whether the token exists.
62
     */
63 15
    public function offsetExists($offset): bool
64
    {
65 15
        return isset($this->children[$this->calculateOffset($offset)]);
66
    }
67
68
    /**
69
     * Returns a child token at the specified offset.
70
     *
71
     * This method is required by the SPL {@see ArrayAccess} interface. It is implicitly called when you use something
72
     * like `$child = $token[$offset];`.
73
     *
74
     * @param int $offset child token offset.
75
     *
76
     * @return SqlToken|null the child token at the specified offset, `null` if there's no token.
77
     */
78 28
    public function offsetGet($offset): self|null
79
    {
80 28
        $offset = $this->calculateOffset($offset);
81
82 28
        return $this->children[$offset] ?? null;
83
    }
84
85
    /**
86
     * Adds a child token to the token.
87
     *
88
     * This method is required by the SPL {@see ArrayAccess} interface. It is implicitly called when you use something
89
     * like `$token[$offset] = $child;`.
90
     *
91
     * @param mixed $offset child token offset.
92
     * @param mixed $value token to be added.
93
     */
94 28
    public function offsetSet(mixed $offset, mixed $value): void
95
    {
96 28
        if ($value instanceof self) {
97 28
            $value->parent = $this;
98
        }
99
100 28
        if ($offset === null) {
101 28
            $this->children[] = $value;
102
        } else {
103
            $this->children[$this->calculateOffset((int) $offset)] = $value;
104
        }
105
106 28
        $this->updateCollectionOffsets();
107
    }
108
109
    /**
110
     * Removes a child token at the specified offset.
111
     *
112
     * This method is required by the SPL {@see ArrayAccess} interface. It is implicitly called when you use something
113
     * like `unset($token[$offset])`.
114
     *
115
     * @param int $offset child token offset.
116
     */
117 12
    public function offsetUnset($offset): void
118
    {
119 12
        $offset = $this->calculateOffset($offset);
120
121 12
        if (isset($this->children[$offset])) {
122 12
            array_splice($this->children, $offset, 1);
123
        }
124
125 12
        $this->updateCollectionOffsets();
126
    }
127
128
    /**
129
     * Returns child tokens.
130
     *
131
     * @return SqlToken[] child tokens.
132
     */
133 14
    public function getChildren(): array
134
    {
135 14
        return $this->children;
136
    }
137
138
    /**
139
     * Sets a list of child tokens.
140
     *
141
     * @param SqlToken[] $children child tokens.
142
     */
143 1
    public function setChildren(array $children): void
144
    {
145 1
        $this->children = [];
146
147 1
        foreach ($children as $child) {
148 1
            $child->parent = $this;
149 1
            $this->children[] = $child;
150
        }
151
152 1
        $this->updateCollectionOffsets();
153
    }
154
155
    /**
156
     * Returns whether the token represents a collection of tokens.
157
     *
158
     * @return bool whether the token represents a collection of tokens.
159
     */
160 28
    public function getIsCollection(): bool
161
    {
162 28
        return in_array($this->type, [self::TYPE_CODE, self::TYPE_STATEMENT, self::TYPE_PARENTHESIS], true);
163
    }
164
165
    /**
166
     * Returns whether the token represents a collection of tokens and has non-zero number of children.
167
     *
168
     * @return bool whether the token has children.
169
     */
170 28
    public function getHasChildren(): bool
171
    {
172 28
        return $this->getIsCollection() && !empty($this->children);
173
    }
174
175
    /**
176
     * Returns the SQL code representing the token.
177
     *
178
     * @return string SQL code.
179
     */
180 16
    public function getSql(): string
181
    {
182 16
        $sql = '';
183 16
        $code = $this;
184
185 16
        while ($code->parent !== null) {
186 16
            $code = $code->parent;
187
        }
188
189 16
        if ($code->content !== null) {
190 16
            $sql = mb_substr(
191 16
                $code->content,
192 16
                (int) $this->startOffset,
193 16
                (int) $this->endOffset - (int) $this->startOffset,
194 16
                'UTF-8',
195 16
            );
196
        }
197
198 16
        return $sql;
199
    }
200
201
    /**
202
     * Returns whether this token (including its children) matches the specified "pattern" SQL code.
203
     *
204
     * Usage Example:
205
     *
206
     * ```php
207
     * $patternToken = (new \Yiisoft\Db\Sqlite\SqlTokenizer('SELECT any FROM any'))->tokenize();
208
     * if ($sqlToken->matches($patternToken, 0, $firstMatchIndex, $lastMatchIndex)) {
209
     *     // ...
210
     * }
211
     * ```
212
     *
213
     * @param SqlToken $patternToken tokenized SQL codes to match against. In addition to normal SQL, the `any` keyword
214
     * is supported which will match any number of keywords, identifiers, whitespaces.
215
     * @param int $offset token children offset to start lookup with.
216
     * @param int|null $firstMatchIndex token children offset where a successful match begins.
217
     * @param int|null $lastMatchIndex  token children offset where a successful match ends.
218
     *
219
     * @return bool whether this token matches the pattern SQL code.
220
     */
221 15
    public function matches(
222
        self $patternToken,
223
        int $offset = 0,
224
        int &$firstMatchIndex = null,
225
        int &$lastMatchIndex = null
226
    ): bool {
227 15
        $result = false;
228
229 15
        if ($patternToken->getHasChildren() && ($patternToken[0] instanceof self)) {
230 15
            $result = $this->tokensMatch($patternToken[0], $this, $offset, $firstMatchIndex, $lastMatchIndex);
0 ignored issues
show
Bug introduced by
It seems like $patternToken[0] can also be of type null; however, parameter $patternToken of Yiisoft\Db\Sqlite\SqlToken::tokensMatch() does only seem to accept Yiisoft\Db\Sqlite\SqlToken, maybe add an additional type check? ( Ignorable by Annotation )

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

230
            $result = $this->tokensMatch(/** @scrutinizer ignore-type */ $patternToken[0], $this, $offset, $firstMatchIndex, $lastMatchIndex);
Loading history...
231
        }
232
233 15
        return $result;
234
    }
235
236
    /**
237
     * Tests the given token to match the specified pattern token.
238
     */
239 15
    private function tokensMatch(
240
        self $patternToken,
241
        self $token,
242
        int $offset = 0,
243
        int &$firstMatchIndex = null,
244
        int &$lastMatchIndex = null
245
    ): bool {
246
        if (
247 15
            $patternToken->getIsCollection() !== $token->getIsCollection() ||
248 15
            (!$patternToken->getIsCollection() && $patternToken->content !== $token->content)
249
        ) {
250 15
            return false;
251
        }
252
253 15
        if ($patternToken->children === $token->children) {
254 15
            $firstMatchIndex = $lastMatchIndex = $offset;
255
256 15
            return true;
257
        }
258
259 15
        $firstMatchIndex = $lastMatchIndex = null;
260 15
        $wildcard = false;
261
262 15
        for ($index = 0, $count = count($patternToken->children); $index < $count; $index++) {
263
            /**
264
             *  Here we iterate token by token with an exception to "any" that toggles an iteration until we matched
265
             *  with a next pattern token or EOF.
266
             */
267 15
            if ($patternToken[$index] instanceof self && $patternToken[$index]->content === 'any') {
268 15
                $wildcard = true;
269 15
                continue;
270
            }
271
272 15
            for ($limit = $wildcard ? count($token->children) : $offset + 1; $offset < $limit; $offset++) {
273 15
                if (!$wildcard && !isset($token[$offset])) {
274
                    break;
275
                }
276
277
                if (
278 15
                    $patternToken[$index] instanceof self &&
279 15
                    $token[$offset] instanceof self  &&
280 15
                    !$this->tokensMatch($patternToken[$index], $token[$offset])
0 ignored issues
show
Bug introduced by
It seems like $patternToken[$index] can also be of type null; however, parameter $patternToken of Yiisoft\Db\Sqlite\SqlToken::tokensMatch() does only seem to accept Yiisoft\Db\Sqlite\SqlToken, maybe add an additional type check? ( Ignorable by Annotation )

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

280
                    !$this->tokensMatch(/** @scrutinizer ignore-type */ $patternToken[$index], $token[$offset])
Loading history...
Bug introduced by
It seems like $token[$offset] can also be of type null; however, parameter $token of Yiisoft\Db\Sqlite\SqlToken::tokensMatch() does only seem to accept Yiisoft\Db\Sqlite\SqlToken, maybe add an additional type check? ( Ignorable by Annotation )

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

280
                    !$this->tokensMatch($patternToken[$index], /** @scrutinizer ignore-type */ $token[$offset])
Loading history...
281
                ) {
282 15
                    continue;
283
                }
284
285 15
                if ($firstMatchIndex === null) {
286 15
                    $firstMatchIndex = $offset;
287
                }
288
289 15
                $lastMatchIndex = $offset;
290 15
                $wildcard = false;
291 15
                $offset++;
292
293 15
                continue 2;
294
            }
295
296 15
            return false;
297
        }
298
299 15
        return true;
300
    }
301
302
    /**
303
     * Returns an absolute offset in the children array.
304
     */
305 28
    private function calculateOffset(int $offset): int
306
    {
307 28
        if ($offset >= 0) {
308 28
            return $offset;
309
        }
310
311 28
        return count($this->children) + $offset;
312
    }
313
314
    /**
315
     * Updates token SQL code start and end offsets based on its children.
316
     */
317 29
    private function updateCollectionOffsets(): void
318
    {
319 29
        if (!empty($this->children)) {
320 29
            $this->startOffset = reset($this->children)->startOffset;
321 29
            $this->endOffset = end($this->children)->endOffset;
322
        }
323
324 29
        $this->parent?->updateCollectionOffsets();
325
    }
326
327
    /**
328
     * Set token type. It has to be one of the following constants:
329
     *
330
     * - {@see TYPE_CODE}
331
     * - {@see TYPE_STATEMENT}
332
     * - {@see TYPE_TOKEN}
333
     * - {@see TYPE_PARENTHESIS}
334
     * - {@see TYPE_KEYWORD}
335
     * - {@see TYPE_OPERATOR}
336
     * - {@see TYPE_IDENTIFIER}
337
     * - {@see TYPE_STRING_LITERAL}
338
     *
339
     * @param int $value token type. It has to be one of the following constants:
340
     */
341 28
    public function type(int $value): self
342
    {
343 28
        $this->type = $value;
344
345 28
        return $this;
346
    }
347
348
    /**
349
     * Set token content.
350
     */
351 30
    public function content(string|null $value): self
352
    {
353 30
        $this->content = $value;
354
355 30
        return $this;
356
    }
357
358
    /**
359
     * Set original SQL token start position.
360
     *
361
     * @param int $value original SQL token start position.
362
     */
363 28
    public function startOffset(int $value): self
364
    {
365 28
        $this->startOffset = $value;
366
367 28
        return $this;
368
    }
369
370
    /**
371
     * Set original SQL token end position.
372
     *
373
     * @param int $value original SQL token end position.
374
     */
375 28
    public function endOffset(int $value): self
376
    {
377 28
        $this->endOffset = $value;
378
379 28
        return $this;
380
    }
381
382
    /**
383
     * Set parent token.
384
     *
385
     * @param SqlToken $value parent token.
386
     */
387
    public function parent(self $value): self
388
    {
389
        $this->parent = $value;
390
391
        return $this;
392
    }
393
394 3
    public function getContent(): string|null
395
    {
396 3
        return $this->content;
397
    }
398
399
    public function getType(): int
400
    {
401
        return $this->type;
402
    }
403
}
404