Passed
Pull Request — dev (#90)
by Wilmer
06:19 queued 02:38
created

SqlToken::offsetExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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 3
    public function __toString(): string
48
    {
49 3
        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 12
    public function offsetExists($offset): bool
63
    {
64 12
        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 17
    public function offsetGet($offset): ?self
78
    {
79 17
        $offset = $this->calculateOffset($offset);
80
81 17
        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 mixed $offset child token offset.
91
     * @param mixed $value token to be added.
92
     */
93 17
    public function offsetSet(mixed $offset, mixed $value): void
94
    {
95 17
        if ($value instanceof self) {
96 17
            $value->parent = $this;
97
        }
98
99 17
        if ($offset === null) {
100 17
            $this->children[] = $value;
101
        } else {
102
            $this->children[$this->calculateOffset((int) $offset)] = $value;
103
        }
104
105 17
        $this->updateCollectionOffsets();
106
    }
107
108
    /**
109
     * Removes a child token at the specified offset.
110
     *
111
     * This method is required by the SPL {@see ArrayAccess} interface. It is implicitly called when you use something
112
     * like `unset($token[$offset])`.
113
     *
114
     * @param int $offset child token offset.
115
     */
116 5
    public function offsetUnset($offset): void
117
    {
118 5
        $offset = $this->calculateOffset($offset);
119
120 5
        if (isset($this->children[$offset])) {
121 5
            array_splice($this->children, $offset, 1);
122
        }
123
124 5
        $this->updateCollectionOffsets();
125
    }
126
127
    /**
128
     * Returns child tokens.
129
     *
130
     * @return SqlToken[] child tokens.
131
     */
132 5
    public function getChildren(): array
133
    {
134 5
        return $this->children;
135
    }
136
137
    /**
138
     * Sets a list of child tokens.
139
     *
140
     * @param SqlToken[] $children child tokens.
141
     */
142
    public function setChildren(array $children): void
143
    {
144
        $this->children = [];
145
146
        foreach ($children as $child) {
147
            $child->parent = $this;
148
            $this->children[] = $child;
149
        }
150
151
        $this->updateCollectionOffsets();
152
    }
153
154
    /**
155
     * Returns whether the token represents a collection of tokens.
156
     *
157
     * @return bool whether the token represents a collection of tokens.
158
     */
159 17
    public function getIsCollection(): bool
160
    {
161 17
        return in_array($this->type, [self::TYPE_CODE, self::TYPE_STATEMENT, self::TYPE_PARENTHESIS], true);
162
    }
163
164
    /**
165
     * Returns whether the token represents a collection of tokens and has non-zero number of children.
166
     *
167
     * @return bool whether the token has children.
168
     */
169 17
    public function getHasChildren(): bool
170
    {
171 17
        return $this->getIsCollection() && !empty($this->children);
172
    }
173
174
    /**
175
     * Returns the SQL code representing the token.
176
     *
177
     * @return string SQL code.
178
     */
179 8
    public function getSql(): string
180
    {
181 8
        $sql = '';
182 8
        $code = $this;
183
184 8
        while ($code->parent !== null) {
185 8
            $code = $code->parent;
186
        }
187
188 8
        if ($code->content !== null) {
189 8
            $sql = mb_substr(
190 8
                $code->content,
191 8
                (int) $this->startOffset,
192 8
                (int) $this->endOffset - (int) $this->startOffset,
193
                'UTF-8',
194
            );
195
        }
196
197 8
        return $sql;
198
    }
199
200
    /**
201
     * Returns whether this token (including its children) matches the specified "pattern" SQL code.
202
     *
203
     * Usage Example:
204
     *
205
     * ```php
206
     * $patternToken = (new \Yiisoft\Db\Sqlite\SqlTokenizer('SELECT any FROM any'))->tokenize();
207
     * if ($sqlToken->matches($patternToken, 0, $firstMatchIndex, $lastMatchIndex)) {
208
     *     // ...
209
     * }
210
     * ```
211
     *
212
     * @param SqlToken $patternToken tokenized SQL codes to match against. In addition to normal SQL, the `any` keyword
213
     * is supported which will match any number of keywords, identifiers, whitespaces.
214
     * @param int $offset token children offset to start lookup with.
215
     * @param int|null $firstMatchIndex token children offset where a successful match begins.
216
     * @param int|null $lastMatchIndex  token children offset where a successful match ends.
217
     *
218
     * @return bool whether this token matches the pattern SQL code.
219
     */
220 12
    public function matches(
221
        self $patternToken,
222
        int $offset = 0,
223
        ?int &$firstMatchIndex = null,
224
        ?int &$lastMatchIndex = null
225
    ): bool {
226 12
        $result = false;
227
228 12
        if ($patternToken->getHasChildren() && ($patternToken[0] instanceof self)) {
229 12
            $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

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

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

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