Passed
Pull Request — master (#29)
by Wilmer
12:49
created

SqlToken::tokensMatch()   C

Complexity

Conditions 13
Paths 12

Size

Total Lines 56
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 56
rs 6.6166
c 0
b 0
f 0
cc 13
nc 12
nop 5

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

224
        return $this->tokensMatch(/** @scrutinizer ignore-type */ $patternToken, $this, $offset, $firstMatchIndex, $lastMatchIndex);
Loading history...
225
    }
226
227
    /**
228
     * Tests the given token to match the specified pattern token.
229
     *
230
     * @param SqlToken $patternToken
231
     * @param SqlToken $token
232
     * @param int $offset
233
     * @param int|null $firstMatchIndex
234
     * @param int|null $lastMatchIndex
235
     *
236
     * @return bool
237
     */
238
    private function tokensMatch(
239
        self $patternToken,
240
        self $token,
241
        int $offset = 0,
242
        ?int &$firstMatchIndex = null,
243
        ?int &$lastMatchIndex = null
244
    ): bool {
245
        if ($patternToken->getIsCollection() !== $token->getIsCollection() || (!$patternToken->getIsCollection() && $patternToken->content !== $token->content)) {
246
            return false;
247
        }
248
249
        if ($patternToken->children === $token->children) {
250
            $firstMatchIndex = $lastMatchIndex = $offset;
251
252
            return true;
253
        }
254
255
        $firstMatchIndex = $lastMatchIndex = null;
256
        $wildcard = false;
257
258
        for ($index = 0, $count = count($patternToken->children); $index < $count; $index++) {
259
            /**
260
             *  Here we iterate token by token with an exception of "any" that toggles an iteration until we matched
261
             *  with a next pattern token or EOF.
262
             */
263
            if ($patternToken[$index]->content === 'any') {
264
                $wildcard = true;
265
                continue;
266
            }
267
268
            for ($limit = $wildcard ? count($token->children) : $offset + 1; $offset < $limit; $offset++) {
269
                if (!$wildcard && !isset($token[$offset])) {
270
                    break;
271
                }
272
273
                if (!$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

273
                if (!$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

273
                if (!$this->tokensMatch($patternToken[$index], /** @scrutinizer ignore-type */ $token[$offset])) {
Loading history...
274
                    continue;
275
                }
276
277
                if ($firstMatchIndex === null) {
278
                    $firstMatchIndex = $offset;
279
                    $lastMatchIndex = $offset;
280
                } else {
281
                    $lastMatchIndex = $offset;
282
                }
283
284
                $wildcard = false;
285
                $offset++;
286
287
                continue 2;
288
            }
289
290
            return false;
291
        }
292
293
        return true;
294
    }
295
296
    /**
297
     * Returns an absolute offset in the children array.
298
     *
299
     * @param int $offset
300
     *
301
     * @return int
302
     */
303
    private function calculateOffset(int $offset): int
304
    {
305
        if ($offset >= 0) {
306
            return $offset;
307
        }
308
309
        return count($this->children) + $offset;
310
    }
311
312
    /**
313
     * Updates token SQL code start and end offsets based on its children.
314
     */
315
    private function updateCollectionOffsets(): void
316
    {
317
        if (!empty($this->children)) {
318
            $this->startOffset = reset($this->children)->startOffset;
319
            $this->endOffset = end($this->children)->endOffset;
320
        }
321
322
        if ($this->parent !== null) {
323
            $this->parent->updateCollectionOffsets();
324
        }
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
     * @return self
342
     */
343
    public function type(int $value): self
344
    {
345
        $this->type = $value;
346
347
        return $this;
348
    }
349
350
    /**
351
     * Set token content.
352
     *
353
     * @param string|null $value
354
     *
355
     * @return self
356
     */
357
    public function content(?string $value): self
358
    {
359
        $this->content = $value;
360
361
        return $this;
362
    }
363
364
    /**
365
     * Set original SQL token start position.
366
     *
367
     * @param int $value original SQL token start position.
368
     *
369
     * @return self
370
     */
371
    public function startOffset(int $value): self
372
    {
373
        $this->startOffset = $value;
374
375
        return $this;
376
    }
377
378
    /**
379
     * Set original SQL token end position.
380
     *
381
     * @param int $value original SQL token end position.
382
     *
383
     * @return self
384
     */
385
    public function endOffset(int $value): self
386
    {
387
        $this->endOffset = $value;
388
389
        return $this;
390
    }
391
392
    /**
393
     * Set parent token.
394
     *
395
     * @param SqlToken $value parent token.
396
     *
397
     * @return self
398
     */
399
    public function parent(SqlToken $value): self
400
    {
401
        $this->parent = $value;
402
403
        return $this;
404
    }
405
406
    public function getContent(): ?string
407
    {
408
        return $this->content;
409
    }
410
411
    public function getType(): int
412
    {
413
        return $this->type;
414
    }
415
}
416