Passed
Pull Request — master (#520)
by
unknown
03:37
created

Lexer::parseLabel()   B

Complexity

Conditions 8
Paths 3

Size

Total Lines 39
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
eloc 16
nc 3
nop 0
dl 0
loc 39
ccs 17
cts 17
cp 1
crap 8
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpMyAdmin\SqlParser;
6
7
use Exception;
8
use PhpMyAdmin\SqlParser\Exceptions\LexerException;
9
10
use function in_array;
11
use function mb_strlen;
12
use function sprintf;
13
use function str_ends_with;
14
use function strlen;
15
use function substr;
16
17
/**
18
 * Defines the lexer of the library.
19
 *
20
 * This is one of the most important components, along with the parser.
21
 *
22
 * Depends on context to extract lexemes.
23
 *
24
 * Performs lexical analysis over a SQL statement and splits it in multiple tokens.
25
 *
26
 * The output of the lexer is affected by the context of the SQL statement.
27
 *
28
 * @see Context
29
 */
30
class Lexer
31
{
32
    /**
33
     * Whether errors should throw exceptions or just be stored.
34
     */
35
    private bool $strict = false;
36
37
    /**
38
     * List of errors that occurred during lexing.
39
     *
40
     * Usually, the lexing does not stop once an error occurred because that
41
     * error might be false positive or a partial result (even a bad one)
42
     * might be needed.
43
     *
44
     * @var Exception[]
45
     */
46
    public array $errors = [];
47
48
    /**
49
     * A list of keywords that indicate that the function keyword
50
     * is not used as a function
51
     */
52
    private const KEYWORD_NAME_INDICATORS = [
53
        'FROM',
54
        'SET',
55
        'WHERE',
56
    ];
57
58
    /**
59
     * A list of operators that indicate that the function keyword
60
     * is not used as a function
61
     */
62
    private const OPERATOR_NAME_INDICATORS = [
63
        ',',
64
        '.',
65
    ];
66
67
    /**
68
     * The string to be parsed.
69
     *
70
     * @var string|UtfString
71
     */
72
    public $str = '';
73
74
    /**
75
     * The length of `$str`.
76
     *
77
     * By storing its length, a lot of time is saved, because parsing methods
78
     * would call `strlen` everytime.
79
     *
80
     * @var int
81
     */
82
    public $len = 0;
83
84
    /**
85
     * The index of the last parsed character.
86
     *
87
     * @var int
88
     */
89
    public $last = 0;
90
91
    /**
92
     * Tokens extracted from given strings.
93
     *
94
     * @var TokensList
95
     */
96
    public $list;
97
98
    /**
99
     * The default delimiter. This is used, by default, in all new instances.
100
     *
101
     * @var string
102
     */
103
    public static $defaultDelimiter = ';';
104
105
    /**
106
     * Statements delimiter.
107
     * This may change during lexing.
108
     *
109
     * @var string
110
     */
111
    public $delimiter;
112
113
    /**
114
     * The length of the delimiter.
115
     *
116
     * Because `parseDelimiter` can be called a lot, it would perform a lot of
117
     * calls to `strlen`, which might affect performance when the delimiter is
118
     * big.
119
     *
120
     * @var int
121
     */
122
    public $delimiterLen;
123
124
    /**
125
     * @param string|UtfString $str       the query to be lexed
126
     * @param bool             $strict    whether strict mode should be
127
     *                                    enabled or not
128
     * @param string           $delimiter the delimiter to be used
129
     */
130 1444
    public function __construct($str, $strict = false, $delimiter = null)
131
    {
132 1444
        if (Context::$keywords === []) {
133
            Context::load();
134
        }
135
136
        // `strlen` is used instead of `mb_strlen` because the lexer needs to
137
        // parse each byte of the input.
138 1444
        $len = $str instanceof UtfString ? $str->length() : strlen($str);
139
140
        // For multi-byte strings, a new instance of `UtfString` is initialized.
141 1444
        if (! $str instanceof UtfString && $len !== mb_strlen($str, 'UTF-8')) {
142 10
            $str = new UtfString($str);
143
        }
144
145 1444
        $this->str = $str;
146 1444
        $this->len = $str instanceof UtfString ? $str->length() : $len;
147
148 1444
        $this->strict = $strict;
149
150
        // Setting the delimiter.
151 1444
        $this->setDelimiter(! empty($delimiter) ? $delimiter : static::$defaultDelimiter);
152
153 1444
        $this->lex();
154
    }
155
156
    /**
157
     * Sets the delimiter.
158
     *
159
     * @param string $delimiter the new delimiter
160
     */
161 1444
    public function setDelimiter($delimiter): void
162
    {
163 1444
        $this->delimiter = $delimiter;
164 1444
        $this->delimiterLen = strlen($delimiter);
165
    }
166
167
    /**
168
     * Parses the string and extracts lexemes.
169
     */
170 1444
    public function lex(): void
171
    {
172
        // TODO: Sometimes, static::parse* functions make unnecessary calls to
173
        // is* functions. For a better performance, some rules can be deduced
174
        // from context.
175
        // For example, in `parseBool` there is no need to compare the token
176
        // every time with `true` and `false`. The first step would be to
177
        // compare with 'true' only and just after that add another letter from
178
        // context and compare again with `false`.
179
        // Another example is `parseComment`.
180
181 1444
        $list = new TokensList();
182
183
        /**
184
         * Last processed token.
185
         */
186 1444
        $lastToken = null;
187
188 1444
        for ($this->last = 0, $lastIdx = 0; $this->last < $this->len; $lastIdx = ++$this->last) {
189 1434
            $token = $this->parse();
190
191 1434
            if ($token === null) {
192
                // @assert($this->last === $lastIdx);
193 6
                $token = new Token($this->str[$this->last]);
194 6
                $this->error('Unexpected character.', $this->str[$this->last], $this->last);
195
            } elseif (
196 1434
                $lastToken !== null
197 1434
                && $token->type === TokenType::Symbol
198 1434
                && $token->flags & Token::FLAG_SYMBOL_VARIABLE
199
                && (
200 1434
                    $lastToken->type === TokenType::String
201 1434
                    || (
202 1434
                        $lastToken->type === TokenType::Symbol
203 1434
                        && $lastToken->flags & Token::FLAG_SYMBOL_BACKTICK
204 1434
                    )
205
                )
206
            ) {
207
                // Handles ```... FROM 'user'@'%' ...```.
208 46
                $lastToken->token .= $token->token;
209 46
                $lastToken->type = TokenType::Symbol;
210 46
                $lastToken->flags = Token::FLAG_SYMBOL_USER;
211 46
                $lastToken->value .= '@' . $token->value;
212 46
                continue;
213
            } elseif (
214 1434
                $lastToken !== null
215 1434
                && $token->type === TokenType::Keyword
216 1434
                && $lastToken->type === TokenType::Operator
217 1434
                && $lastToken->value === '.'
218
            ) {
219
                // Handles ```... tbl.FROM ...```. In this case, FROM is not
220
                // a reserved word.
221 30
                $token->type = TokenType::None;
222 30
                $token->flags = 0;
223 30
                $token->value = $token->token;
224
            }
225
226 1434
            $token->position = $lastIdx;
227
228 1434
            $list->tokens[$list->count++] = $token;
229
230
            // Handling delimiters.
231 1434
            if ($token->type === TokenType::None && $token->value === 'DELIMITER') {
232 36
                if ($this->last + 1 >= $this->len) {
233 2
                    $this->error('Expected whitespace(s) before delimiter.', '', $this->last + 1);
234 2
                    continue;
235
                }
236
237
                // Skipping last R (from `delimiteR`) and whitespaces between
238
                // the keyword `DELIMITER` and the actual delimiter.
239 34
                $pos = ++$this->last;
240 34
                $token = $this->parseWhitespace();
241
242 34
                if ($token !== null) {
243 32
                    $token->position = $pos;
244 32
                    $list->tokens[$list->count++] = $token;
245
                }
246
247
                // Preparing the token that holds the new delimiter.
248 34
                if ($this->last + 1 >= $this->len) {
249 2
                    $this->error('Expected delimiter.', '', $this->last + 1);
250 2
                    continue;
251
                }
252
253 32
                $pos = $this->last + 1;
254
255
                // Parsing the delimiter.
256 32
                $this->delimiter = null;
257 32
                $delimiterLen = 0;
258
                while (
259 32
                    ++$this->last < $this->len
260 32
                    && ! Context::isWhitespace($this->str[$this->last])
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last] can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isWhitespace() does only seem to accept string, 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

260
                    && ! Context::isWhitespace(/** @scrutinizer ignore-type */ $this->str[$this->last])
Loading history...
261 32
                    && $delimiterLen < 15
262
                ) {
263 30
                    $this->delimiter .= $this->str[$this->last];
264 30
                    ++$delimiterLen;
265
                }
266
267 32
                if (empty($this->delimiter)) {
268 2
                    $this->error('Expected delimiter.', '', $this->last);
269 2
                    $this->delimiter = ';';
270
                }
271
272 32
                --$this->last;
273
274
                // Saving the delimiter and its token.
275 32
                $this->delimiterLen = strlen($this->delimiter);
276 32
                $token = new Token($this->delimiter, TokenType::Delimiter);
277 32
                $token->position = $pos;
278 32
                $list->tokens[$list->count++] = $token;
279
            }
280
281 1430
            $lastToken = $token;
282
        }
283
284
        // Adding a final delimiter to mark the ending.
285 1444
        $list->tokens[$list->count++] = new Token(null, TokenType::Delimiter);
286
287
        // Saving the tokens list.
288 1444
        $this->list = $list;
289
290 1444
        $this->solveAmbiguityOnStarOperator();
291 1444
        $this->solveAmbiguityOnFunctionKeywords();
292
    }
293
294
    /**
295
     * Resolves the ambiguity when dealing with the "*" operator.
296
     *
297
     * In SQL statements, the "*" operator can be an arithmetic operator (like in 2*3) or an SQL wildcard (like in
298
     * SELECT a.* FROM ...). To solve this ambiguity, the solution is to find the next token, excluding whitespaces and
299
     * comments, right after the "*" position. The "*" is for sure an SQL wildcard if the next token found is any of:
300
     * - "FROM" (the FROM keyword like in "SELECT * FROM...");
301
     * - "USING" (the USING keyword like in "DELETE table_name.* USING...");
302
     * - "," (a comma separator like in "SELECT *, field FROM...");
303
     * - ")" (a closing parenthesis like in "COUNT(*)").
304
     * This methods will change the flag of the "*" tokens when any of those condition above is true. Otherwise, the
305
     * default flag (arithmetic) will be kept.
306
     */
307 1444
    private function solveAmbiguityOnStarOperator(): void
308
    {
309 1444
        $iBak = $this->list->idx;
310 1444
        while (($starToken = $this->list->getNextOfTypeAndValue(TokenType::Operator, '*')) !== null) {
311
            // getNext() already gets rid of whitespaces and comments.
312 198
            $next = $this->list->getNext();
313
314 198
            if ($next === null) {
315
                continue;
316
            }
317
318
            if (
319 198
                ($next->type !== TokenType::Keyword || ! in_array($next->value, ['FROM', 'USING'], true))
320 198
                && ($next->type !== TokenType::Operator || ! in_array($next->value, [',', ')'], true))
321
            ) {
322 16
                continue;
323
            }
324
325 184
            $starToken->flags = Token::FLAG_OPERATOR_SQL;
326
        }
327
328 1444
        $this->list->idx = $iBak;
329
    }
330
331
    /**
332
     * Resolves the ambiguity when dealing with the functions keywords.
333
     *
334
     * In SQL statements, the function keywords might be used as table names or columns names.
335
     * To solve this ambiguity, the solution is to find the next token, excluding whitespaces and
336
     * comments, right after the function keyword position. The function keyword is for sure used
337
     * as column name or table name if the next token found is any of:
338
     *
339
     * - "FROM" (the FROM keyword like in "SELECT Country x, AverageSalary avg FROM...");
340
     * - "WHERE" (the WHERE keyword like in "DELETE FROM emp x WHERE x.salary = 20");
341
     * - "SET" (the SET keyword like in "UPDATE Country x, City y set x.Name=x.Name");
342
     * - "," (a comma separator like 'x,' in "UPDATE Country x, City y set x.Name=x.Name");
343
     * - "." (a dot separator like in "x.asset_id FROM (SELECT evt.asset_id FROM evt)".
344
     * - "NULL" (when used as a table alias like in "avg.col FROM (SELECT ev.col FROM ev) avg").
345
     *
346
     * This method will change the flag of the function keyword tokens when any of those
347
     * condition above is true. Otherwise, the
348
     * default flag (function keyword) will be kept.
349
     */
350 1444
    private function solveAmbiguityOnFunctionKeywords(): void
351
    {
352 1444
        $iBak = $this->list->idx;
353 1444
        $keywordFunction = TokenType::Keyword->value | Token::FLAG_KEYWORD_FUNCTION;
354 1444
        while (($keywordToken = $this->list->getNextOfTypeAndFlag(TokenType::Keyword, $keywordFunction)) !== null) {
355 214
            $next = $this->list->getNext();
356
            if (
357 214
                ($next->type !== TokenType::Keyword
358 214
                    || ! in_array($next->value, self::KEYWORD_NAME_INDICATORS, true)
359
                )
360 214
                && ($next->type !== TokenType::Operator
361 214
                    || ! in_array($next->value, self::OPERATOR_NAME_INDICATORS, true)
362
                )
363 214
                && ($next->value !== null)
364
            ) {
365 204
                continue;
366
            }
367
368 12
            $keywordToken->type = TokenType::None;
369 12
            $keywordToken->flags = Token::FLAG_NONE;
370 12
            $keywordToken->keyword = $keywordToken->value;
371
        }
372
373 1444
        $this->list->idx = $iBak;
374
    }
375
376
    /**
377
     * Creates a new error log.
378
     *
379
     * @param string $msg  the error message
380
     * @param string $str  the character that produced the error
381
     * @param int    $pos  the position of the character
382
     * @param int    $code the code of the error
383
     *
384
     * @throws LexerException throws the exception, if strict mode is enabled.
385
     */
386 34
    public function error($msg, $str = '', $pos = 0, $code = 0): void
387
    {
388 34
        $error = new LexerException(
389 34
            Translator::gettext($msg),
390 34
            $str,
391 34
            $pos,
392 34
            $code
393 34
        );
394
395 34
        if ($this->strict) {
396 2
            throw $error;
397
        }
398
399 32
        $this->errors[] = $error;
400
    }
401
402
    /**
403
     * Parses a keyword.
404
     */
405 1416
    public function parseKeyword(): Token|null
406
    {
407 1416
        $token = '';
408
409
        /**
410
         * Value to be returned.
411
         *
412
         * @var Token
413
         */
414 1416
        $ret = null;
415
416
        /**
417
         * The value of `$this->last` where `$token` ends in `$this->str`.
418
         */
419 1416
        $iEnd = $this->last;
420
421
        /**
422
         * Whether last parsed character is a whitespace.
423
         *
424
         * @var bool
425
         */
426 1416
        $lastSpace = false;
427
428 1416
        for ($j = 1; $j < Context::KEYWORD_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
429
            // Composed keywords shouldn't have more than one whitespace between
430
            // keywords.
431 1416
            if (Context::isWhitespace($this->str[$this->last])) {
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last] can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isWhitespace() does only seem to accept string, 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

431
            if (Context::isWhitespace(/** @scrutinizer ignore-type */ $this->str[$this->last])) {
Loading history...
432 1380
                if ($lastSpace) {
433 270
                    --$j; // The size of the keyword didn't increase.
434 270
                    continue;
435
                }
436
437 1380
                $lastSpace = true;
438
            } else {
439 1416
                $lastSpace = false;
440
            }
441
442 1416
            $token .= $this->str[$this->last];
443 1416
            $flags = Context::isKeyword($token);
444
445 1416
            if (($this->last + 1 !== $this->len && ! Context::isSeparator($this->str[$this->last + 1])) || ! $flags) {
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last + 1] can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isSeparator() does only seem to accept string, 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

445
            if (($this->last + 1 !== $this->len && ! Context::isSeparator(/** @scrutinizer ignore-type */ $this->str[$this->last + 1])) || ! $flags) {
Loading history...
Bug Best Practice introduced by
The expression $flags of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
446 1416
                continue;
447
            }
448
449 1380
            $ret = new Token($token, TokenType::Keyword, $flags);
450 1380
            $iEnd = $this->last;
451
452
            // We don't break so we find longest keyword.
453
            // For example, `OR` and `ORDER` have a common prefix `OR`.
454
            // If we stopped at `OR`, the parsing would be invalid.
455
        }
456
457 1416
        $this->last = $iEnd;
458
459 1416
        return $ret;
460
    }
461
462
    /**
463
     * Parses a label.
464
     */
465 1064
    public function parseLabel(): Token|null
466
    {
467 1064
        $token = '';
468
469
        /**
470
         * Value to be returned.
471
         *
472
         * @var Token
473
         */
474 1064
        $ret = null;
475
476
        /**
477
         * The value of `$this->last` where `$token` ends in `$this->str`.
478
         */
479 1064
        $iEnd = $this->last;
480 1064
        for ($j = 1; $j < Context::LABEL_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
481 1064
            if ($this->str[$this->last] === ':' && $j > 1) {
482
                // End of label
483 4
                $token .= $this->str[$this->last];
484 4
                $ret = new Token($token, TokenType::Label);
485 4
                $iEnd = $this->last;
486 4
                break;
487
            }
488
489 1064
            if (Context::isWhitespace($this->str[$this->last]) && $j > 1) {
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last] can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isWhitespace() does only seem to accept string, 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

489
            if (Context::isWhitespace(/** @scrutinizer ignore-type */ $this->str[$this->last]) && $j > 1) {
Loading history...
490
                // Whitespace between label and :
491
                // The size of the keyword didn't increase.
492 828
                --$j;
493 1064
            } elseif (Context::isSeparator($this->str[$this->last])) {
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last] can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isSeparator() does only seem to accept string, 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

493
            } elseif (Context::isSeparator(/** @scrutinizer ignore-type */ $this->str[$this->last])) {
Loading history...
494
                // Any other separator
495 812
                break;
496
            }
497
498 1060
            $token .= $this->str[$this->last];
499
        }
500
501 1064
        $this->last = $iEnd;
502
503 1064
        return $ret;
504
    }
505
506
    /**
507
     * Parses an operator.
508
     */
509 1434
    public function parseOperator(): Token|null
510
    {
511 1434
        $token = '';
512
513
        /**
514
         * Value to be returned.
515
         *
516
         * @var Token
517
         */
518 1434
        $ret = null;
519
520
        /**
521
         * The value of `$this->last` where `$token` ends in `$this->str`.
522
         */
523 1434
        $iEnd = $this->last;
524
525 1434
        for ($j = 1; $j < Context::OPERATOR_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
526 1434
            $token .= $this->str[$this->last];
527 1434
            $flags = Context::isOperator($token);
528
529 1434
            if (! $flags) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $flags of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
530 1430
                continue;
531
            }
532
533 1026
            $ret = new Token($token, TokenType::Operator, $flags);
534 1026
            $iEnd = $this->last;
535
        }
536
537 1434
        $this->last = $iEnd;
538
539 1434
        return $ret;
540
    }
541
542
    /**
543
     * Parses a whitespace.
544
     */
545 1434
    public function parseWhitespace(): Token|null
546
    {
547 1434
        $token = $this->str[$this->last];
548
549 1434
        if (! Context::isWhitespace($token)) {
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isWhitespace() does only seem to accept string, 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

549
        if (! Context::isWhitespace(/** @scrutinizer ignore-type */ $token)) {
Loading history...
550 1434
            return null;
551
        }
552
553 1396
        while (++$this->last < $this->len && Context::isWhitespace($this->str[$this->last])) {
554 274
            $token .= $this->str[$this->last];
555
        }
556
557 1396
        --$this->last;
558
559 1396
        return new Token($token, TokenType::Whitespace);
560
    }
561
562
    /**
563
     * Parses a comment.
564
     */
565 1434
    public function parseComment(): Token|null
566
    {
567 1434
        $iBak = $this->last;
568 1434
        $token = $this->str[$this->last];
569
570
        // Bash style comments. (#comment\n)
571 1434
        if (Context::isComment($token)) {
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isComment() does only seem to accept string, 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

571
        if (Context::isComment(/** @scrutinizer ignore-type */ $token)) {
Loading history...
Bug Best Practice introduced by
The expression PhpMyAdmin\SqlParser\Context::isComment($token) of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
572 6
            while (++$this->last < $this->len && $this->str[$this->last] !== "\n") {
573 6
                $token .= $this->str[$this->last];
574
            }
575
576
            // Include trailing \n as whitespace token
577 6
            if ($this->last < $this->len) {
578 6
                --$this->last;
579
            }
580
581 6
            return new Token($token, TokenType::Comment, Token::FLAG_COMMENT_BASH);
582
        }
583
584
        // C style comments. (/*comment*\/)
585 1434
        if (++$this->last < $this->len) {
586 1430
            $token .= $this->str[$this->last];
587 1430
            if (Context::isComment($token)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression PhpMyAdmin\SqlParser\Context::isComment($token) of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
588
                // There might be a conflict with "*" operator here, when string is "*/*".
589
                // This can occurs in the following statements:
590
                // - "SELECT */* comment */ FROM ..."
591
                // - "SELECT 2*/* comment */3 AS `six`;"
592 100
                $next = $this->last + 1;
593 100
                if (($next < $this->len) && $this->str[$next] === '*') {
594
                    // Conflict in "*/*": first "*" was not for ending a comment.
595
                    // Stop here and let other parsing method define the true behavior of that first star.
596 2
                    $this->last = $iBak;
597
598 2
                    return null;
599
                }
600
601 100
                $flags = Token::FLAG_COMMENT_C;
602
603
                // This comment already ended. It may be a part of a
604
                // previous MySQL specific command.
605 100
                if ($token === '*/') {
606 36
                    return new Token($token, TokenType::Comment, $flags);
607
                }
608
609
                // Checking if this is a MySQL-specific command.
610 98
                if ($this->last + 1 < $this->len && $this->str[$this->last + 1] === '!') {
611 34
                    $flags |= Token::FLAG_COMMENT_MYSQL_CMD;
612 34
                    $token .= $this->str[++$this->last];
613
614
                    while (
615 34
                        ++$this->last < $this->len
616 34
                        && $this->str[$this->last] >= '0'
617 34
                        && $this->str[$this->last] <= '9'
618
                    ) {
619 32
                        $token .= $this->str[$this->last];
620
                    }
621
622 34
                    --$this->last;
623
624
                    // We split this comment and parse only its beginning
625
                    // here.
626 34
                    return new Token($token, TokenType::Comment, $flags);
627
                }
628
629
                // Parsing the comment.
630
                while (
631 68
                    ++$this->last < $this->len
632 68
                    && (
633 68
                        $this->str[$this->last - 1] !== '*'
634 68
                        || $this->str[$this->last] !== '/'
635 68
                    )
636
                ) {
637 68
                    $token .= $this->str[$this->last];
638
                }
639
640
                // Adding the ending.
641 68
                if ($this->last < $this->len) {
642 68
                    $token .= $this->str[$this->last];
643
                }
644
645 68
                return new Token($token, TokenType::Comment, $flags);
646
            }
647
        }
648
649
        // SQL style comments. (-- comment\n)
650 1434
        if (++$this->last < $this->len) {
651 1428
            $token .= $this->str[$this->last];
652 1428
            $end = false;
653
        } else {
654 418
            --$this->last;
655 418
            $end = true;
656
        }
657
658 1434
        if (Context::isComment($token, $end)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression PhpMyAdmin\SqlParser\Con...isComment($token, $end) of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
659
            // Checking if this comment did not end already (```--\n```).
660 70
            if ($this->str[$this->last] !== "\n") {
661 70
                while (++$this->last < $this->len && $this->str[$this->last] !== "\n") {
662 70
                    $token .= $this->str[$this->last];
663
                }
664
            }
665
666
            // Include trailing \n as whitespace token
667 70
            if ($this->last < $this->len) {
668 62
                --$this->last;
669
            }
670
671 70
            return new Token($token, TokenType::Comment, Token::FLAG_COMMENT_SQL);
672
        }
673
674 1434
        $this->last = $iBak;
675
676 1434
        return null;
677
    }
678
679
    /**
680
     * Parses a boolean.
681
     */
682 1418
    public function parseBool(): Token|null
683
    {
684 1418
        if ($this->last + 3 >= $this->len) {
685
            // At least `min(strlen('TRUE'), strlen('FALSE'))` characters are
686
            // required.
687 316
            return null;
688
        }
689
690 1418
        $iBak = $this->last;
691 1418
        $token = $this->str[$this->last] . $this->str[++$this->last]
692 1418
        . $this->str[++$this->last] . $this->str[++$this->last]; // _TRUE_ or _FALS_e
693
694 1418
        if (Context::isBool($token)) {
695 4
            return new Token($token, TokenType::Bool);
696
        }
697
698 1418
        if (++$this->last < $this->len) {
699 1414
            $token .= $this->str[$this->last]; // fals_E_
700 1414
            if (Context::isBool($token)) {
701 6
                return new Token($token, TokenType::Bool, 1);
702
            }
703
        }
704
705 1418
        $this->last = $iBak;
706
707 1418
        return null;
708
    }
709
710
    /**
711
     * Parses a number.
712
     */
713 1434
    public function parseNumber(): Token|null
714
    {
715
        // A rudimentary state machine is being used to parse numbers due to
716
        // the various forms of their notation.
717
        //
718
        // Below are the states of the machines and the conditions to change
719
        // the state.
720
        //
721
        //      1 --------------------[ + or - ]-------------------> 1
722
        //      1 -------------------[ 0x or 0X ]------------------> 2
723
        //      1 --------------------[ 0 to 9 ]-------------------> 3
724
        //      1 -----------------------[ . ]---------------------> 4
725
        //      1 -----------------------[ b ]---------------------> 7
726
        //
727
        //      2 --------------------[ 0 to F ]-------------------> 2
728
        //
729
        //      3 --------------------[ 0 to 9 ]-------------------> 3
730
        //      3 -----------------------[ . ]---------------------> 4
731
        //      3 --------------------[ e or E ]-------------------> 5
732
        //
733
        //      4 --------------------[ 0 to 9 ]-------------------> 4
734
        //      4 --------------------[ e or E ]-------------------> 5
735
        //
736
        //      5 ---------------[ + or - or 0 to 9 ]--------------> 6
737
        //
738
        //      7 -----------------------[ ' ]---------------------> 8
739
        //
740
        //      8 --------------------[ 0 or 1 ]-------------------> 8
741
        //      8 -----------------------[ ' ]---------------------> 9
742
        //
743
        // State 1 may be reached by negative numbers.
744
        // State 2 is reached only by hex numbers.
745
        // State 4 is reached only by float numbers.
746
        // State 5 is reached only by numbers in approximate form.
747
        // State 7 is reached only by numbers in bit representation.
748
        //
749
        // Valid final states are: 2, 3, 4 and 6. Any parsing that finished in a
750
        // state other than these is invalid.
751
        // Also, negative states are invalid states.
752 1434
        $iBak = $this->last;
753 1434
        $token = '';
754 1434
        $flags = 0;
755 1434
        $state = 1;
756 1434
        for (; $this->last < $this->len; ++$this->last) {
757 1434
            if ($state === 1) {
758 1434
                if ($this->str[$this->last] === '-') {
759 70
                    $flags |= Token::FLAG_NUMBER_NEGATIVE;
760
                } elseif (
761 1434
                    $this->last + 1 < $this->len
762 1434
                    && $this->str[$this->last] === '0'
763 1434
                    && $this->str[$this->last + 1] === 'x'
764
                ) {
765 4
                    $token .= $this->str[$this->last++];
766 4
                    $state = 2;
767 1434
                } elseif ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9') {
768 638
                    $state = 3;
769 1432
                } elseif ($this->str[$this->last] === '.') {
770 224
                    $state = 4;
771 1432
                } elseif ($this->str[$this->last] === 'b') {
772 108
                    $state = 7;
773 1432
                } elseif ($this->str[$this->last] !== '+') {
774
                    // `+` is a valid character in a number.
775 1433
                    break;
776
                }
777 740
            } elseif ($state === 2) {
778 4
                $flags |= Token::FLAG_NUMBER_HEX;
779
                if (
780
                    ! (
781 4
                        ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9')
782 4
                        || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'F')
783 4
                        || ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'f')
784
                    )
785
                ) {
786 4
                    break;
787
                }
788 740
            } elseif ($state === 3) {
789 578
                if ($this->str[$this->last] === '.') {
790 12
                    $state = 4;
791 576
                } elseif ($this->str[$this->last] === 'e' || $this->str[$this->last] === 'E') {
792 2
                    $state = 5;
793
                } elseif (
794 576
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
795 576
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
796
                ) {
797
                    // A number can't be directly followed by a letter
798 10
                    $state = -$state;
799 572
                } elseif ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
800
                    // Just digits and `.`, `e` and `E` are valid characters.
801 570
                    break;
802
                }
803 320
            } elseif ($state === 4) {
804 234
                $flags |= Token::FLAG_NUMBER_FLOAT;
805 234
                if ($this->str[$this->last] === 'e' || $this->str[$this->last] === 'E') {
806 14
                    $state = 5;
807
                } elseif (
808 234
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
809 234
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
810
                ) {
811
                    // A number can't be directly followed by a letter
812 174
                    $state = -$state;
813 94
                } elseif ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
814
                    // Just digits, `e` and `E` are valid characters.
815 163
                    break;
816
                }
817 270
            } elseif ($state === 5) {
818 14
                $flags |= Token::FLAG_NUMBER_APPROXIMATE;
819
                if (
820 14
                    $this->str[$this->last] === '+' || $this->str[$this->last] === '-'
821 14
                    || ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9')
822
                ) {
823 2
                    $state = 6;
824
                } elseif (
825 14
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
826 14
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
827
                ) {
828
                    // A number can't be directly followed by a letter
829 14
                    $state = -$state;
830
                } else {
831 7
                    break;
832
                }
833 270
            } elseif ($state === 6) {
834 2
                if ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
835
                    // Just digits are valid characters.
836 2
                    break;
837
                }
838 270
            } elseif ($state === 7) {
839 106
                $flags |= Token::FLAG_NUMBER_BINARY;
840 106
                if ($this->str[$this->last] !== '\'') {
841 104
                    break;
842
                }
843
844 2
                $state = 8;
845 184
            } elseif ($state === 8) {
846 2
                if ($this->str[$this->last] === '\'') {
847 2
                    $state = 9;
848 2
                } elseif ($this->str[$this->last] !== '0' && $this->str[$this->last] !== '1') {
849 2
                    break;
850
                }
851 184
            } elseif ($state === 9) {
852 2
                break;
853
            }
854
855 824
            $token .= $this->str[$this->last];
856
        }
857
858 1434
        if ($state === 2 || $state === 3 || ($token !== '.' && $state === 4) || $state === 6 || $state === 9) {
859 638
            --$this->last;
860
861 638
            return new Token($token, TokenType::Number, $flags);
862
        }
863
864 1434
        $this->last = $iBak;
865
866 1434
        return null;
867
    }
868
869
    /**
870
     * Parses a string.
871
     *
872
     * @param string $quote additional starting symbol
873
     *
874
     * @throws LexerException
875
     */
876 1418
    public function parseString($quote = ''): Token|null
877
    {
878 1418
        $token = $this->str[$this->last];
879 1418
        $flags = Context::isString($token);
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isString() does only seem to accept string, 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

879
        $flags = Context::isString(/** @scrutinizer ignore-type */ $token);
Loading history...
880
881 1418
        if (! $flags && $token !== $quote) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $flags of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
882 1418
            return null;
883
        }
884
885 696
        $quote = $token;
886
887 696
        while (++$this->last < $this->len) {
888
            if (
889 696
                $this->last + 1 < $this->len
890
                && (
891 696
                    ($this->str[$this->last] === $quote && $this->str[$this->last + 1] === $quote)
892 696
                    || ($this->str[$this->last] === '\\' && $quote !== '`')
893
                )
894
            ) {
895 30
                $token .= $this->str[$this->last] . $this->str[++$this->last];
896
            } else {
897 696
                if ($this->str[$this->last] === $quote) {
898 692
                    break;
899
                }
900
901 690
                $token .= $this->str[$this->last];
902
            }
903
        }
904
905 696
        if ($this->last >= $this->len || $this->str[$this->last] !== $quote) {
906 14
            $this->error(
907 14
                sprintf(
908 14
                    Translator::gettext('Ending quote %1$s was expected.'),
909 14
                    $quote
910 14
                ),
911 14
                '',
912 14
                $this->last
913 14
            );
914
        } else {
915 692
            $token .= $this->str[$this->last];
916
        }
917
918 696
        return new Token($token, TokenType::String, $flags);
919
    }
920
921
    /**
922
     * Parses a symbol.
923
     *
924
     * @throws LexerException
925
     */
926 1418
    public function parseSymbol(): Token|null
927
    {
928 1418
        $token = $this->str[$this->last];
929 1418
        $flags = Context::isSymbol($token);
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isSymbol() does only seem to accept string, 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

929
        $flags = Context::isSymbol(/** @scrutinizer ignore-type */ $token);
Loading history...
930
931 1418
        if (! $flags) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $flags of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
932 1416
            return null;
933
        }
934
935 468
        if ($flags & Token::FLAG_SYMBOL_VARIABLE) {
936 122
            if ($this->last + 1 < $this->len && $this->str[++$this->last] === '@') {
937
                // This is a system variable (e.g. `@@hostname`).
938 26
                $token .= $this->str[$this->last++];
939 74
                $flags |= Token::FLAG_SYMBOL_SYSTEM;
940
            }
941 378
        } elseif ($flags & Token::FLAG_SYMBOL_PARAMETER) {
942 18
            if ($token !== '?' && $this->last + 1 < $this->len) {
943 13
                ++$this->last;
944
            }
945
        } else {
946 366
            $token = '';
947
        }
948
949 468
        $str = null;
950
951 468
        if ($this->last < $this->len) {
952 468
            $str = $this->parseString('`');
953
954 468
            if ($str === null) {
955 100
                $str = $this->parseUnknown();
956
957 100
                if ($str === null && ! ($flags & Token::FLAG_SYMBOL_PARAMETER)) {
958 4
                    $this->error('Variable name was expected.', $this->str[$this->last], $this->last);
959
                }
960
            }
961
        }
962
963 468
        if ($str !== null) {
964 458
            $token .= $str->token;
965
        }
966
967 468
        return new Token($token, TokenType::Symbol, $flags);
968
    }
969
970
    /**
971
     * Parses unknown parts of the query.
972
     */
973 1092
    public function parseUnknown(): Token|null
974
    {
975 1092
        $token = $this->str[$this->last];
976 1092
        if (Context::isSeparator($token)) {
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isSeparator() does only seem to accept string, 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

976
        if (Context::isSeparator(/** @scrutinizer ignore-type */ $token)) {
Loading history...
977 22
            return null;
978
        }
979
980 1084
        while (++$this->last < $this->len && ! Context::isSeparator($this->str[$this->last])) {
981 1052
            $token .= $this->str[$this->last];
982
983
            // Test if end of token equals the current delimiter. If so, remove it from the token.
984 1052
            if (str_ends_with($token, $this->delimiter)) {
985 4
                $token = substr($token, 0, -$this->delimiterLen);
986 4
                $this->last -= $this->delimiterLen - 1;
987 4
                break;
988
            }
989
        }
990
991 1084
        --$this->last;
992
993 1084
        return new Token($token);
994
    }
995
996
    /**
997
     * Parses the delimiter of the query.
998
     */
999 1434
    public function parseDelimiter(): Token|null
1000
    {
1001 1434
        $idx = 0;
1002
1003 1434
        while ($idx < $this->delimiterLen && $this->last + $idx < $this->len) {
1004 1434
            if ($this->delimiter[$idx] !== $this->str[$this->last + $idx]) {
1005 1434
                return null;
1006
            }
1007
1008 578
            ++$idx;
1009
        }
1010
1011 578
        $this->last += $this->delimiterLen - 1;
1012
1013 578
        return new Token($this->delimiter, TokenType::Delimiter);
1014
    }
1015
1016 1434
    private function parse(): Token|null
1017
    {
1018
        // It is best to put the parsers in order of their complexity
1019
        // (ascending) and their occurrence rate (descending).
1020
        //
1021
        // Conflicts:
1022
        //
1023
        // 1. `parseDelimiter`, `parseUnknown`, `parseKeyword`, `parseNumber`
1024
        // They fight over delimiter. The delimiter may be a keyword, a
1025
        // number or almost any character which makes the delimiter one of
1026
        // the first tokens that must be parsed.
1027
        //
1028
        // 1. `parseNumber` and `parseOperator`
1029
        // They fight over `+` and `-`.
1030
        //
1031
        // 2. `parseComment` and `parseOperator`
1032
        // They fight over `/` (as in ```/*comment*/``` or ```a / b```)
1033
        //
1034
        // 3. `parseBool` and `parseKeyword`
1035
        // They fight over `TRUE` and `FALSE`.
1036
        //
1037
        // 4. `parseKeyword` and `parseUnknown`
1038
        // They fight over words. `parseUnknown` does not know about
1039
        // keywords.
1040
1041 1434
        return $this->parseDelimiter()
1042 1434
            ?? $this->parseWhitespace()
1043 1434
            ?? $this->parseNumber()
1044 1434
            ?? $this->parseComment()
1045 1434
            ?? $this->parseOperator()
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->parseOperator() targeting PhpMyAdmin\SqlParser\Lexer::parseOperator() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1046 1434
            ?? $this->parseBool()
1047 1434
            ?? $this->parseString()
1048 1434
            ?? $this->parseSymbol()
1049 1434
            ?? $this->parseKeyword()
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->parseKeyword() targeting PhpMyAdmin\SqlParser\Lexer::parseKeyword() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1050 1434
            ?? $this->parseLabel()
1051 1434
            ?? $this->parseUnknown();
1052
    }
1053
}
1054