Passed
Branch master (e82d75)
by Wilmer
07:17 queued 02:54
created

SqlToken::getContent()   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 0
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, \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|null $startOffset = null;
38
    private int|null $endOffset = null;
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 4
    public function __toString(): string
48
    {
49 4
        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 15
    public function offsetExists($offset): bool
63
    {
64 15
        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 21
    public function offsetGet($offset): self|null
78
    {
79 21
        $offset = $this->calculateOffset($offset);
80
81 21
        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 21
    public function offsetSet(mixed $offset, mixed $value): void
94
    {
95 21
        if ($value instanceof self) {
96 21
            $value->parent = $this;
97
        }
98
99 21
        if ($offset === null) {
100 21
            $this->children[] = $value;
101
        } else {
102
            $this->children[$this->calculateOffset((int) $offset)] = $value;
103
        }
104
105 21
        $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 6
    public function getChildren(): array
133
    {
134 6
        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 21
    public function getIsCollection(): bool
160
    {
161 21
        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 21
    public function getHasChildren(): bool
170
    {
171 21
        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 9
    public function getSql(): string
180
    {
181 9
        $sql = '';
182 9
        $code = $this;
183
184 9
        while ($code->parent !== null) {
185 9
            $code = $code->parent;
186
        }
187
188 9
        if ($code->content !== null) {
189 9
            $sql = mb_substr(
190 9
                $code->content,
191 9
                (int) $this->startOffset,
192 9
                (int) $this->endOffset - (int) $this->startOffset,
193 9
                'UTF-8',
194 9
            );
195
        }
196
197 9
        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 15
    public function matches(
221
        self $patternToken,
222
        int $offset = 0,
223
        int &$firstMatchIndex = null,
224
        int &$lastMatchIndex = null
225
    ): bool {
226 15
        $result = false;
227
228 15
        if ($patternToken->getHasChildren() && ($patternToken[0] instanceof self)) {
229 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

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

279
                    !$this->tokensMatch($patternToken[$index], /** @scrutinizer ignore-type */ $token[$offset])
Loading history...
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

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