Test Failed
Pull Request — master (#82)
by Wilmer
24:21 queued 13:10
created

SqlToken::getType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Sqlite;
6
7
use ArrayAccess;
8
9
use function array_splice;
10
use function count;
11
use function end;
12
use function in_array;
13
use function mb_substr;
14
use function reset;
15
16
/**
17
 * SqlToken represents SQL tokens produced by {@see SqlTokenizer} or its child classes.
18
 *
19
 * @property SqlToken[] $children Child tokens.
20
 * @property bool $hasChildren Whether the token has children. This property is read-only.
21
 * @property bool $isCollection Whether the token represents a collection of tokens. This property is
22
 * read-only.
23
 * @property string $sql SQL code. This property is read-only.
24
 */
25
final class SqlToken implements ArrayAccess
26
{
27
    public const TYPE_CODE = 0;
28
    public const TYPE_STATEMENT = 1;
29
    public const TYPE_TOKEN = 2;
30
    public const TYPE_PARENTHESIS = 3;
31
    public const TYPE_KEYWORD = 4;
32
    public const TYPE_OPERATOR = 5;
33
    public const TYPE_IDENTIFIER = 6;
34
    public const TYPE_STRING_LITERAL = 7;
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 2
    {
49
        return $this->getSql();
50 2
    }
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 17
    {
64
        return isset($this->children[$this->calculateOffset($offset)]);
65 17
    }
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): ?self
78 22
    {
79
        $offset = $this->calculateOffset($offset);
80 22
81
        return $this->children[$offset] ?? null;
82 22
    }
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 22
    {
95
        $token->parent = $this;
96 22
97
        if ($offset === null) {
98 22
            $this->children[] = $token;
99 22
        } else {
100
            $this->children[$this->calculateOffset($offset)] = $token;
101
        }
102
103
        $this->updateCollectionOffsets();
104 22
    }
105 22
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 5
    {
116
        $offset = $this->calculateOffset($offset);
117 5
118
        if (isset($this->children[$offset])) {
119 5
            array_splice($this->children, $offset, 1);
120 5
        }
121
122
        $this->updateCollectionOffsets();
123 5
    }
124 5
125
    /**
126
     * Returns child tokens.
127
     *
128
     * @return SqlToken[] child tokens.
129
     */
130
    public function getChildren(): array
131 7
    {
132
        return $this->children;
133 7
    }
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 22
    {
159
        return in_array($this->type, [self::TYPE_CODE, self::TYPE_STATEMENT, self::TYPE_PARENTHESIS], true);
160 22
    }
161 22
162 22
    /**
163 22
     * Returns whether the token represents a collection of tokens and has non-zero number of children.
164 22
     *
165
     * @return bool whether the token has children.
166
     */
167
    public function getHasChildren(): bool
168
    {
169
        return $this->getIsCollection() && !empty($this->children);
170
    }
171
172 22
    /**
173
     * Returns the SQL code representing the token.
174 22
     *
175
     * @return string SQL code.
176
     */
177
    public function getSql(): string
178
    {
179
        $sql = '';
180
        $code = $this;
181
182 13
        while ($code->parent !== null) {
183
            $code = $code->parent;
184 13
        }
185
186 13
        if ($code->content !== null) {
187 13
            $sql = mb_substr(
188
                $code->content,
189
                (int) $this->startOffset,
190 13
                (int) $this->endOffset - (int) $this->startOffset,
191
                'UTF-8',
192
            );
193
        }
194
195
        return $sql;
196
    }
197
198
    /**
199
     * Returns whether this token (including its children) matches the specified "pattern" SQL code.
200
     *
201
     * Usage Example:
202
     *
203
     * ```php
204
     * $patternToken = (new \Yiisoft\Db\Sqlite\SqlTokenizer('SELECT any FROM any'))->tokenize();
205
     * if ($sqlToken->matches($patternToken, 0, $firstMatchIndex, $lastMatchIndex)) {
206
     *     // ...
207
     * }
208
     * ```
209
     *
210
     * @param SqlToken $patternToken tokenized SQL code to match against. In addition to normal SQL, the `any` keyword
211
     * is supported which will match any number of keywords, identifiers, whitespaces.
212
     * @param int $offset token children offset to start lookup with.
213 17
     * @param int|null $firstMatchIndex token children offset where a successful match begins.
214
     * @param int|null $lastMatchIndex  token children offset where a successful match ends.
215
     *
216
     * @return bool whether this token matches the pattern SQL code.
217
     */
218
    public function matches(
219 17
        self $patternToken,
220
        int $offset = 0,
221
        ?int &$firstMatchIndex = null,
222
        ?int &$lastMatchIndex = null
223 17
    ): bool {
224
        $result = false;
225 17
226
        if ($patternToken->getHasChildren() && ($patternToken[0] instanceof self)) {
227
            $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

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

285
                    !$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

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