Passed
Pull Request — master (#133)
by Wilmer
20:38 queued 16:37
created

SqlToken::parent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
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, \Stringable
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|null $content = null;
37
    private int $startOffset = 0;
38
    private int $endOffset = 0;
39
    private SqlToken|null $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 20
    public function offsetGet($offset): self|null
78
    {
79 20
        $offset = $this->calculateOffset($offset);
80
81 20
        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 20
    public function offsetSet(mixed $offset, mixed $value): void
94
    {
95 20
        if ($value instanceof self) {
96 20
            $value->parent = $this;
97
        }
98
99 20
        if ($offset === null) {
100 20
            $this->children[] = $value;
101
        } else {
102
            $this->children[$this->calculateOffset((int) $offset)] = $value;
103
        }
104
105 20
        $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 9
    public function getChildren(): array
133
    {
134 9
        return $this->children;
135
    }
136
137
    /**
138
     * Sets a list of child tokens.
139
     *
140
     * @param SqlToken[] $children child tokens.
141
     */
142 1
    public function setChildren(array $children): void
143
    {
144 1
        $this->children = [];
145
146 1
        foreach ($children as $child) {
147 1
            $child->parent = $this;
148 1
            $this->children[] = $child;
149
        }
150
151 1
        $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 20
    public function getIsCollection(): bool
160
    {
161 20
        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 20
    public function getHasChildren(): bool
170
    {
171 20
        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
        $code = $this;
182
183 8
        while ($code->parent !== null) {
184 8
            $code = $code->parent;
185
        }
186
187 8
        return $code->content !== null
188 8
            ? mb_substr($code->content, $this->startOffset, $this->endOffset - $this->startOffset, 'UTF-8')
189 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 codes 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 12
    public function matches(
213
        self $patternToken,
214
        int $offset = 0,
215
        int &$firstMatchIndex = null,
216
        int &$lastMatchIndex = null
217
    ): bool {
218 12
        $result = false;
219
220 12
        if ($patternToken->getHasChildren() && ($patternToken[0] instanceof self)) {
221 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

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

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

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