Passed
Push — master ( 3589fa...c4e763 )
by
unknown
04:11
created

Lexer::lex()   D

Complexity

Conditions 24
Paths 76

Size

Total Lines 136
Code Lines 68

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 64
CRAP Score 24

Importance

Changes 0
Metric Value
cc 24
eloc 68
c 0
b 0
f 0
nc 76
nop 0
dl 0
loc 136
ccs 64
cts 64
cp 1
crap 24
rs 4.1666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpMyAdmin\SqlParser;
6
7
use PhpMyAdmin\SqlParser\Exceptions\LexerException;
8
9
use function define;
10
use function defined;
11
use function in_array;
12
use function mb_strlen;
13
use function sprintf;
14
use function str_ends_with;
15
use function strlen;
16
use function substr;
17
18 7
if (! defined('USE_UTF_STRINGS')) {
19
    // NOTE: In previous versions of PHP (5.5 and older) the default
20
    // internal encoding is "ISO-8859-1".
21
    // All `mb_` functions must specify the correct encoding, which is
22
    // 'UTF-8' in order to work properly.
23
24
    /*
25
     * Forces usage of `UtfString` if the string is multibyte.
26
     * `UtfString` may be slower, but it gives better results.
27
     *
28
     * @var bool
29
     */
30 7
    define('USE_UTF_STRINGS', true);
31
}
32
33
/**
34
 * Defines the lexer of the library.
35
 *
36
 * This is one of the most important components, along with the parser.
37
 *
38
 * Depends on context to extract lexemes.
39
 *
40
 * Performs lexical analysis over a SQL statement and splits it in multiple tokens.
41
 *
42
 * The output of the lexer is affected by the context of the SQL statement.
43
 *
44
 * @see Context
45
 */
46
class Lexer extends Core
47
{
48
    /**
49
     * A list of methods that are used in lexing the SQL query.
50
     *
51
     * @var string[]
52
     */
53
    public static $PARSER_METHODS = [
54
        // It is best to put the parsers in order of their complexity
55
        // (ascending) and their occurrence rate (descending).
56
        //
57
        // Conflicts:
58
        //
59
        // 1. `parseDelimiter`, `parseUnknown`, `parseKeyword`, `parseNumber`
60
        // They fight over delimiter. The delimiter may be a keyword, a
61
        // number or almost any character which makes the delimiter one of
62
        // the first tokens that must be parsed.
63
        //
64
        // 1. `parseNumber` and `parseOperator`
65
        // They fight over `+` and `-`.
66
        //
67
        // 2. `parseComment` and `parseOperator`
68
        // They fight over `/` (as in ```/*comment*/``` or ```a / b```)
69
        //
70
        // 3. `parseBool` and `parseKeyword`
71
        // They fight over `TRUE` and `FALSE`.
72
        //
73
        // 4. `parseKeyword` and `parseUnknown`
74
        // They fight over words. `parseUnknown` does not know about
75
        // keywords.
76
77
        'parseDelimiter',
78
        'parseWhitespace',
79
        'parseNumber',
80
        'parseComment',
81
        'parseOperator',
82
        'parseBool',
83
        'parseString',
84
        'parseSymbol',
85
        'parseKeyword',
86
        'parseLabel',
87
        'parseUnknown',
88
    ];
89
90
    /**
91
     * The string to be parsed.
92
     *
93
     * @var string|UtfString
94
     */
95
    public $str = '';
96
97
    /**
98
     * The length of `$str`.
99
     *
100
     * By storing its length, a lot of time is saved, because parsing methods
101
     * would call `strlen` everytime.
102
     *
103
     * @var int
104
     */
105
    public $len = 0;
106
107
    /**
108
     * The index of the last parsed character.
109
     *
110
     * @var int
111
     */
112
    public $last = 0;
113
114
    /**
115
     * Tokens extracted from given strings.
116
     *
117
     * @var TokensList
118
     */
119
    public $list;
120
121
    /**
122
     * The default delimiter. This is used, by default, in all new instances.
123
     *
124
     * @var string
125
     */
126
    public static $DEFAULT_DELIMITER = ';';
127
128
    /**
129
     * Statements delimiter.
130
     * This may change during lexing.
131
     *
132
     * @var string
133
     */
134
    public $delimiter;
135
136
    /**
137
     * The length of the delimiter.
138
     *
139
     * Because `parseDelimiter` can be called a lot, it would perform a lot of
140
     * calls to `strlen`, which might affect performance when the delimiter is
141
     * big.
142
     *
143
     * @var int
144
     */
145
    public $delimiterLen;
146
147
    /**
148
     * Gets the tokens list parsed by a new instance of a lexer.
149
     *
150
     * @param string|UtfString $str       the query to be lexed
151
     * @param bool             $strict    whether strict mode should be
152
     *                                    enabled or not
153
     * @param string           $delimiter the delimiter to be used
154
     *
155
     * @return TokensList
156
     */
157 4
    public static function getTokens($str, $strict = false, $delimiter = null)
158
    {
159 4
        $lexer = new self($str, $strict, $delimiter);
160
161 4
        return $lexer->list;
162
    }
163
164
    /**
165
     * @param string|UtfString $str       the query to be lexed
166
     * @param bool             $strict    whether strict mode should be
167
     *                                    enabled or not
168
     * @param string           $delimiter the delimiter to be used
169
     */
170 2252
    public function __construct($str, $strict = false, $delimiter = null)
171
    {
172
        // `strlen` is used instead of `mb_strlen` because the lexer needs to
173
        // parse each byte of the input.
174 2252
        $len = $str instanceof UtfString ? $str->length() : strlen($str);
175
176
        // For multi-byte strings, a new instance of `UtfString` is
177
        // initialized (only if `UtfString` usage is forced.
178 2252
        if (! $str instanceof UtfString && USE_UTF_STRINGS && $len !== mb_strlen($str, 'UTF-8')) {
179 4
            $str = new UtfString($str);
180
        }
181
182 2252
        $this->str = $str;
183 2252
        $this->len = $str instanceof UtfString ? $str->length() : $len;
184
185 2252
        $this->strict = $strict;
186
187
        // Setting the delimiter.
188 2252
        $this->setDelimiter(! empty($delimiter) ? $delimiter : static::$DEFAULT_DELIMITER);
189
190 2252
        $this->lex();
191 2252
    }
192
193
    /**
194
     * Sets the delimiter.
195
     *
196
     * @param string $delimiter the new delimiter
197
     *
198
     * @return void
199
     */
200 2252
    public function setDelimiter($delimiter)
201
    {
202 2252
        $this->delimiter = $delimiter;
203 2252
        $this->delimiterLen = strlen($delimiter);
204 2252
    }
205
206
    /**
207
     * Parses the string and extracts lexemes.
208
     *
209
     * @return void
210
     */
211 2252
    public function lex()
212
    {
213
        // TODO: Sometimes, static::parse* functions make unnecessary calls to
214
        // is* functions. For a better performance, some rules can be deduced
215
        // from context.
216
        // For example, in `parseBool` there is no need to compare the token
217
        // every time with `true` and `false`. The first step would be to
218
        // compare with 'true' only and just after that add another letter from
219
        // context and compare again with `false`.
220
        // Another example is `parseComment`.
221
222 2252
        $list = new TokensList();
223
224
        /**
225
         * Last processed token.
226
         *
227
         * @var Token
228
         */
229 2252
        $lastToken = null;
230
231 2252
        for ($this->last = 0, $lastIdx = 0; $this->last < $this->len; $lastIdx = ++$this->last) {
232
            /**
233
             * The new token.
234
             *
235
             * @var Token
236
             */
237 2228
            $token = null;
238
239 2228
            foreach (static::$PARSER_METHODS as $method) {
240 2228
                $token = $this->$method();
241
242 2228
                if ($token) {
243 2228
                    break;
244
                }
245
            }
246
247 2228
            if ($token === null) {
248
                // @assert($this->last === $lastIdx);
249 8
                $token = new Token($this->str[$this->last]);
250 8
                $this->error('Unexpected character.', $this->str[$this->last], $this->last);
251
            } elseif (
252 2228
                $lastToken !== null
253 2228
                && $token->type === Token::TYPE_SYMBOL
254 2228
                && $token->flags & Token::FLAG_SYMBOL_VARIABLE
255
                && (
256 148
                    $lastToken->type === Token::TYPE_STRING
257
                    || (
258 124
                        $lastToken->type === Token::TYPE_SYMBOL
259 2228
                        && $lastToken->flags & Token::FLAG_SYMBOL_BACKTICK
260
                    )
261
                )
262
            ) {
263
                // Handles ```... FROM 'user'@'%' ...```.
264 52
                $lastToken->token .= $token->token;
265 52
                $lastToken->type = Token::TYPE_SYMBOL;
266 52
                $lastToken->flags = Token::FLAG_SYMBOL_USER;
267 52
                $lastToken->value .= '@' . $token->value;
268 52
                continue;
269
            } elseif (
270 2228
                $lastToken !== null
271 2228
                && $token->type === Token::TYPE_KEYWORD
272 2228
                && $lastToken->type === Token::TYPE_OPERATOR
273 2228
                && $lastToken->value === '.'
274
            ) {
275
                // Handles ```... tbl.FROM ...```. In this case, FROM is not
276
                // a reserved word.
277 32
                $token->type = Token::TYPE_NONE;
278 32
                $token->flags = 0;
279 32
                $token->value = $token->token;
280
            }
281
282 2228
            $token->position = $lastIdx;
283
284 2228
            $list->tokens[$list->count++] = $token;
285
286
            // Handling delimiters.
287 2228
            if ($token->type === Token::TYPE_NONE && $token->value === 'DELIMITER') {
288 32
                if ($this->last + 1 >= $this->len) {
289 4
                    $this->error('Expected whitespace(s) before delimiter.', '', $this->last + 1);
290 4
                    continue;
291
                }
292
293
                // Skipping last R (from `delimiteR`) and whitespaces between
294
                // the keyword `DELIMITER` and the actual delimiter.
295 28
                $pos = ++$this->last;
296 28
                $token = $this->parseWhitespace();
297
298 28
                if ($token !== null) {
299 24
                    $token->position = $pos;
300 24
                    $list->tokens[$list->count++] = $token;
301
                }
302
303
                // Preparing the token that holds the new delimiter.
304 28
                if ($this->last + 1 >= $this->len) {
305 4
                    $this->error('Expected delimiter.', '', $this->last + 1);
306 4
                    continue;
307
                }
308
309 24
                $pos = $this->last + 1;
310
311
                // Parsing the delimiter.
312 24
                $this->delimiter = null;
313 24
                $delimiterLen = 0;
314
                while (
315 24
                    ++$this->last < $this->len
316 24
                    && ! Context::isWhitespace($this->str[$this->last])
317 24
                    && $delimiterLen < 15
318
                ) {
319 20
                    $this->delimiter .= $this->str[$this->last];
320 20
                    ++$delimiterLen;
321
                }
322
323 24
                if (empty($this->delimiter)) {
324 4
                    $this->error('Expected delimiter.', '', $this->last);
325 4
                    $this->delimiter = ';';
326
                }
327
328 24
                --$this->last;
329
330
                // Saving the delimiter and its token.
331 24
                $this->delimiterLen = strlen($this->delimiter);
332 24
                $token = new Token($this->delimiter, Token::TYPE_DELIMITER);
333 24
                $token->position = $pos;
334 24
                $list->tokens[$list->count++] = $token;
335
            }
336
337 2220
            $lastToken = $token;
338
        }
339
340
        // Adding a final delimiter to mark the ending.
341 2252
        $list->tokens[$list->count++] = new Token(null, Token::TYPE_DELIMITER);
342
343
        // Saving the tokens list.
344 2252
        $this->list = $list;
345
346 2252
        $this->solveAmbiguityOnStarOperator();
347 2252
    }
348
349
    /**
350
     * Resolves the ambiguity when dealing with the "*" operator.
351
     *
352
     * In SQL statements, the "*" operator can be an arithmetic operator (like in 2*3) or an SQL wildcard (like in
353
     * SELECT a.* FROM ...). To solve this ambiguity, the solution is to find the next token, excluding whitespaces and
354
     * comments, right after the "*" position. The "*" is for sure an SQL wildcard if the next token found is any of:
355
     * - "FROM" (the FROM keyword like in "SELECT * FROM...");
356
     * - "USING" (the USING keyword like in "DELETE table_name.* USING...");
357
     * - "," (a comma separator like in "SELECT *, field FROM...");
358
     * - ")" (a closing parenthesis like in "COUNT(*)").
359
     * This methods will change the flag of the "*" tokens when any of those condition above is true. Otherwise, the
360
     * default flag (arithmetic) will be kept.
361
     *
362
     * @return void
363
     */
364 2252
    private function solveAmbiguityOnStarOperator()
365
    {
366 2252
        $iBak = $this->list->idx;
367 2252
        while (($starToken = $this->list->getNextOfTypeAndValue(Token::TYPE_OPERATOR, '*')) !== null) {
368
            // getNext() already gets rid of whitespaces and comments.
369 348
            $next = $this->list->getNext();
370
371 348
            if ($next === null) {
372
                continue;
373
            }
374
375
            if (
376 348
                ($next->type !== Token::TYPE_KEYWORD || ! in_array($next->value, ['FROM', 'USING'], true))
377 348
                && ($next->type !== Token::TYPE_OPERATOR || ! in_array($next->value, [',', ')'], true))
378
            ) {
379 28
                continue;
380
            }
381
382 324
            $starToken->flags = Token::FLAG_OPERATOR_SQL;
383
        }
384
385 2252
        $this->list->idx = $iBak;
386 2252
    }
387
388
    /**
389
     * Creates a new error log.
390
     *
391
     * @param string $msg  the error message
392
     * @param string $str  the character that produced the error
393
     * @param int    $pos  the position of the character
394
     * @param int    $code the code of the error
395
     *
396
     * @return void
397
     *
398
     * @throws LexerException throws the exception, if strict mode is enabled.
399
     */
400 68
    public function error($msg, $str = '', $pos = 0, $code = 0)
401
    {
402 68
        $error = new LexerException(
403 68
            Translator::gettext($msg),
404 17
            $str,
405 17
            $pos,
406 17
            $code
407
        );
408 68
        parent::error($error);
409 64
    }
410
411
    /**
412
     * Parses a keyword.
413
     *
414
     * @return Token|null
415
     */
416 2192
    public function parseKeyword()
417
    {
418 2192
        $token = '';
419
420
        /**
421
         * Value to be returned.
422
         *
423
         * @var Token
424
         */
425 2192
        $ret = null;
426
427
        /**
428
         * The value of `$this->last` where `$token` ends in `$this->str`.
429
         */
430 2192
        $iEnd = $this->last;
431
432
        /**
433
         * Whether last parsed character is a whitespace.
434
         *
435
         * @var bool
436
         */
437 2192
        $lastSpace = false;
438
439 2192
        for ($j = 1; $j < Context::KEYWORD_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
440
            // Composed keywords shouldn't have more than one whitespace between
441
            // keywords.
442 2192
            if (Context::isWhitespace($this->str[$this->last])) {
443 2144
                if ($lastSpace) {
444 372
                    --$j; // The size of the keyword didn't increase.
445 372
                    continue;
446
                }
447
448 2144
                $lastSpace = true;
449
            } else {
450 2192
                $lastSpace = false;
451
            }
452
453 2192
            $token .= $this->str[$this->last];
454 2192
            $flags = Context::isKeyword($token);
455
456 2192
            if (($this->last + 1 !== $this->len && ! Context::isSeparator($this->str[$this->last + 1])) || ! $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...
457 2192
                continue;
458
            }
459
460 2124
            $ret = new Token($token, Token::TYPE_KEYWORD, $flags);
461 2124
            $iEnd = $this->last;
462
463
            // We don't break so we find longest keyword.
464
            // For example, `OR` and `ORDER` have a common prefix `OR`.
465
            // If we stopped at `OR`, the parsing would be invalid.
466
        }
467
468 2192
        $this->last = $iEnd;
469
470 2192
        return $ret;
471
    }
472
473
    /**
474
     * Parses a label.
475
     *
476
     * @return Token|null
477
     */
478 1624
    public function parseLabel()
479
    {
480 1624
        $token = '';
481
482
        /**
483
         * Value to be returned.
484
         *
485
         * @var Token
486
         */
487 1624
        $ret = null;
488
489
        /**
490
         * The value of `$this->last` where `$token` ends in `$this->str`.
491
         */
492 1624
        $iEnd = $this->last;
493 1624
        for ($j = 1; $j < Context::LABEL_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
494 1624
            if ($this->str[$this->last] === ':' && $j > 1) {
495
                // End of label
496 8
                $token .= $this->str[$this->last];
497 8
                $ret = new Token($token, Token::TYPE_LABEL);
498 8
                $iEnd = $this->last;
499 8
                break;
500
            }
501
502 1624
            if (Context::isWhitespace($this->str[$this->last]) && $j > 1) {
503
                // Whitespace between label and :
504
                // The size of the keyword didn't increase.
505 1268
                --$j;
506 1624
            } elseif (Context::isSeparator($this->str[$this->last])) {
507
                // Any other separator
508 1260
                break;
509
            }
510
511 1620
            $token .= $this->str[$this->last];
512
        }
513
514 1624
        $this->last = $iEnd;
515
516 1624
        return $ret;
517
    }
518
519
    /**
520
     * Parses an operator.
521
     *
522
     * @return Token|null
523
     */
524 2228
    public function parseOperator()
525
    {
526 2228
        $token = '';
527
528
        /**
529
         * Value to be returned.
530
         *
531
         * @var Token
532
         */
533 2228
        $ret = null;
534
535
        /**
536
         * The value of `$this->last` where `$token` ends in `$this->str`.
537
         */
538 2228
        $iEnd = $this->last;
539
540 2228
        for ($j = 1; $j < Context::OPERATOR_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
541 2228
            $token .= $this->str[$this->last];
542 2228
            $flags = Context::isOperator($token);
543
544 2228
            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...
545 2220
                continue;
546
            }
547
548 1584
            $ret = new Token($token, Token::TYPE_OPERATOR, $flags);
549 1584
            $iEnd = $this->last;
550
        }
551
552 2228
        $this->last = $iEnd;
553
554 2228
        return $ret;
555
    }
556
557
    /**
558
     * Parses a whitespace.
559
     *
560
     * @return Token|null
561
     */
562 2228
    public function parseWhitespace()
563
    {
564 2228
        $token = $this->str[$this->last];
565
566 2228
        if (! Context::isWhitespace($token)) {
567 2228
            return null;
568
        }
569
570 2176
        while (++$this->last < $this->len && Context::isWhitespace($this->str[$this->last])) {
571 372
            $token .= $this->str[$this->last];
572
        }
573
574 2176
        --$this->last;
575
576 2176
        return new Token($token, Token::TYPE_WHITESPACE);
577
    }
578
579
    /**
580
     * Parses a comment.
581
     *
582
     * @return Token|null
583
     */
584 2228
    public function parseComment()
585
    {
586 2228
        $iBak = $this->last;
587 2228
        $token = $this->str[$this->last];
588
589
        // Bash style comments. (#comment\n)
590 2228
        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...
591 12
            while (++$this->last < $this->len && $this->str[$this->last] !== "\n") {
592 12
                $token .= $this->str[$this->last];
593
            }
594
595
            // Include trailing \n as whitespace token
596 12
            if ($this->last < $this->len) {
597 12
                --$this->last;
598
            }
599
600 12
            return new Token($token, Token::TYPE_COMMENT, Token::FLAG_COMMENT_BASH);
601
        }
602
603
        // C style comments. (/*comment*\/)
604 2228
        if (++$this->last < $this->len) {
605 2220
            $token .= $this->str[$this->last];
606 2220
            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...
607
                // There might be a conflict with "*" operator here, when string is "*/*".
608
                // This can occurs in the following statements:
609
                // - "SELECT */* comment */ FROM ..."
610
                // - "SELECT 2*/* comment */3 AS `six`;"
611 132
                $next = $this->last + 1;
612 132
                if (($next < $this->len) && $this->str[$next] === '*') {
613
                    // Conflict in "*/*": first "*" was not for ending a comment.
614
                    // Stop here and let other parsing method define the true behavior of that first star.
615 4
                    $this->last = $iBak;
616
617 4
                    return null;
618
                }
619
620 132
                $flags = Token::FLAG_COMMENT_C;
621
622
                // This comment already ended. It may be a part of a
623
                // previous MySQL specific command.
624 132
                if ($token === '*/') {
625 12
                    return new Token($token, Token::TYPE_COMMENT, $flags);
626
                }
627
628
                // Checking if this is a MySQL-specific command.
629 132
                if ($this->last + 1 < $this->len && $this->str[$this->last + 1] === '!') {
630 12
                    $flags |= Token::FLAG_COMMENT_MYSQL_CMD;
631 12
                    $token .= $this->str[++$this->last];
632
633
                    while (
634 12
                        ++$this->last < $this->len
635 12
                        && $this->str[$this->last] >= '0'
636 12
                        && $this->str[$this->last] <= '9'
637
                    ) {
638 8
                        $token .= $this->str[$this->last];
639
                    }
640
641 12
                    --$this->last;
642
643
                    // We split this comment and parse only its beginning
644
                    // here.
645 12
                    return new Token($token, Token::TYPE_COMMENT, $flags);
646
                }
647
648
                // Parsing the comment.
649
                while (
650 128
                    ++$this->last < $this->len
651
                    && (
652 128
                        $this->str[$this->last - 1] !== '*'
653 128
                        || $this->str[$this->last] !== '/'
654
                    )
655
                ) {
656 128
                    $token .= $this->str[$this->last];
657
                }
658
659
                // Adding the ending.
660 128
                if ($this->last < $this->len) {
661 128
                    $token .= $this->str[$this->last];
662
                }
663
664 128
                return new Token($token, Token::TYPE_COMMENT, $flags);
665
            }
666
        }
667
668
        // SQL style comments. (-- comment\n)
669 2228
        if (++$this->last < $this->len) {
670 2216
            $token .= $this->str[$this->last];
671 2216
            $end = false;
672
        } else {
673 704
            --$this->last;
674 704
            $end = true;
675
        }
676
677 2228
        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...
678
            // Checking if this comment did not end already (```--\n```).
679 96
            if ($this->str[$this->last] !== "\n") {
680 96
                while (++$this->last < $this->len && $this->str[$this->last] !== "\n") {
681 96
                    $token .= $this->str[$this->last];
682
                }
683
            }
684
685
            // Include trailing \n as whitespace token
686 96
            if ($this->last < $this->len) {
687 80
                --$this->last;
688
            }
689
690 96
            return new Token($token, Token::TYPE_COMMENT, Token::FLAG_COMMENT_SQL);
691
        }
692
693 2228
        $this->last = $iBak;
694
695 2228
        return null;
696
    }
697
698
    /**
699
     * Parses a boolean.
700
     *
701
     * @return Token|null
702
     */
703 2196
    public function parseBool()
704
    {
705 2196
        if ($this->last + 3 >= $this->len) {
706
            // At least `min(strlen('TRUE'), strlen('FALSE'))` characters are
707
            // required.
708 532
            return null;
709
        }
710
711 2196
        $iBak = $this->last;
712 2196
        $token = $this->str[$this->last] . $this->str[++$this->last]
713 2196
        . $this->str[++$this->last] . $this->str[++$this->last]; // _TRUE_ or _FALS_e
714
715 2196
        if (Context::isBool($token)) {
716 8
            return new Token($token, Token::TYPE_BOOL);
717
        }
718
719 2196
        if (++$this->last < $this->len) {
720 2192
            $token .= $this->str[$this->last]; // fals_E_
721 2192
            if (Context::isBool($token)) {
722 12
                return new Token($token, Token::TYPE_BOOL, 1);
723
            }
724
        }
725
726 2196
        $this->last = $iBak;
727
728 2196
        return null;
729
    }
730
731
    /**
732
     * Parses a number.
733
     *
734
     * @return Token|null
735
     */
736 2228
    public function parseNumber()
737
    {
738
        // A rudimentary state machine is being used to parse numbers due to
739
        // the various forms of their notation.
740
        //
741
        // Below are the states of the machines and the conditions to change
742
        // the state.
743
        //
744
        //      1 --------------------[ + or - ]-------------------> 1
745
        //      1 -------------------[ 0x or 0X ]------------------> 2
746
        //      1 --------------------[ 0 to 9 ]-------------------> 3
747
        //      1 -----------------------[ . ]---------------------> 4
748
        //      1 -----------------------[ b ]---------------------> 7
749
        //
750
        //      2 --------------------[ 0 to F ]-------------------> 2
751
        //
752
        //      3 --------------------[ 0 to 9 ]-------------------> 3
753
        //      3 -----------------------[ . ]---------------------> 4
754
        //      3 --------------------[ e or E ]-------------------> 5
755
        //
756
        //      4 --------------------[ 0 to 9 ]-------------------> 4
757
        //      4 --------------------[ e or E ]-------------------> 5
758
        //
759
        //      5 ---------------[ + or - or 0 to 9 ]--------------> 6
760
        //
761
        //      7 -----------------------[ ' ]---------------------> 8
762
        //
763
        //      8 --------------------[ 0 or 1 ]-------------------> 8
764
        //      8 -----------------------[ ' ]---------------------> 9
765
        //
766
        // State 1 may be reached by negative numbers.
767
        // State 2 is reached only by hex numbers.
768
        // State 4 is reached only by float numbers.
769
        // State 5 is reached only by numbers in approximate form.
770
        // State 7 is reached only by numbers in bit representation.
771
        //
772
        // Valid final states are: 2, 3, 4 and 6. Any parsing that finished in a
773
        // state other than these is invalid.
774
        // Also, negative states are invalid states.
775 2228
        $iBak = $this->last;
776 2228
        $token = '';
777 2228
        $flags = 0;
778 2228
        $state = 1;
779 2228
        for (; $this->last < $this->len; ++$this->last) {
780 2228
            if ($state === 1) {
781 2228
                if ($this->str[$this->last] === '-') {
782 96
                    $flags |= Token::FLAG_NUMBER_NEGATIVE;
783
                } elseif (
784 2228
                    $this->last + 1 < $this->len
785 2228
                    && $this->str[$this->last] === '0'
786
                    && (
787 132
                        $this->str[$this->last + 1] === 'x'
788 2228
                        || $this->str[$this->last + 1] === 'X'
789
                    )
790
                ) {
791 8
                    $token .= $this->str[$this->last++];
792 8
                    $state = 2;
793 2228
                } elseif ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9') {
794 1032
                    $state = 3;
795 2228
                } elseif ($this->str[$this->last] === '.') {
796 336
                    $state = 4;
797 2228
                } elseif ($this->str[$this->last] === 'b') {
798 172
                    $state = 7;
799 2228
                } elseif ($this->str[$this->last] !== '+') {
800
                    // `+` is a valid character in a number.
801 2228
                    break;
802
                }
803 1160
            } elseif ($state === 2) {
804 8
                $flags |= Token::FLAG_NUMBER_HEX;
805
                if (
806
                    ! (
807 8
                        ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9')
808 8
                        || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'F')
809 8
                        || ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'f')
810
                    )
811
                ) {
812 8
                    break;
813
                }
814 1160
            } elseif ($state === 3) {
815 928
                if ($this->str[$this->last] === '.') {
816 24
                    $state = 4;
817 924
                } elseif ($this->str[$this->last] === 'e' || $this->str[$this->last] === 'E') {
818 4
                    $state = 5;
819
                } elseif (
820 924
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
821 924
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
822
                ) {
823
                    // A number can't be directly followed by a letter
824 12
                    $state = -$state;
825 920
                } elseif ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
826
                    // Just digits and `.`, `e` and `E` are valid characters.
827 928
                    break;
828
                }
829 492
            } elseif ($state === 4) {
830 356
                $flags |= Token::FLAG_NUMBER_FLOAT;
831 356
                if ($this->str[$this->last] === 'e' || $this->str[$this->last] === 'E') {
832 28
                    $state = 5;
833
                } elseif (
834 356
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
835 356
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
836
                ) {
837
                    // A number can't be directly followed by a letter
838 248
                    $state = -$state;
839 156
                } elseif ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
840
                    // Just digits, `e` and `E` are valid characters.
841 356
                    break;
842
                }
843 400
            } elseif ($state === 5) {
844 28
                $flags |= Token::FLAG_NUMBER_APPROXIMATE;
845
                if (
846 28
                    $this->str[$this->last] === '+' || $this->str[$this->last] === '-'
847 28
                    || ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9')
848
                ) {
849 4
                    $state = 6;
850
                } elseif (
851 28
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
852 28
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
853
                ) {
854
                    // A number can't be directly followed by a letter
855 28
                    $state = -$state;
856
                } else {
857 28
                    break;
858
                }
859 400
            } elseif ($state === 6) {
860 4
                if ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
861
                    // Just digits are valid characters.
862 4
                    break;
863
                }
864 400
            } elseif ($state === 7) {
865 168
                $flags |= Token::FLAG_NUMBER_BINARY;
866 168
                if ($this->str[$this->last] !== '\'') {
867 164
                    break;
868
                }
869
870 4
                $state = 8;
871 260
            } elseif ($state === 8) {
872 4
                if ($this->str[$this->last] === '\'') {
873 4
                    $state = 9;
874 4
                } elseif ($this->str[$this->last] !== '0' && $this->str[$this->last] !== '1') {
875 4
                    break;
876
                }
877 260
            } elseif ($state === 9) {
878 4
                break;
879
            }
880
881 1292
            $token .= $this->str[$this->last];
882
        }
883
884 2228
        if ($state === 2 || $state === 3 || ($token !== '.' && $state === 4) || $state === 6 || $state === 9) {
885 1032
            --$this->last;
886
887 1032
            return new Token($token, Token::TYPE_NUMBER, $flags);
888
        }
889
890 2228
        $this->last = $iBak;
891
892 2228
        return null;
893
    }
894
895
    /**
896
     * Parses a string.
897
     *
898
     * @param string $quote additional starting symbol
899
     *
900
     * @return Token|null
901
     *
902
     * @throws LexerException
903
     */
904 2196
    public function parseString($quote = '')
905
    {
906 2196
        $token = $this->str[$this->last];
907 2196
        $flags = Context::isString($token);
908
909 2196
        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...
910 2196
            return null;
911
        }
912
913 1088
        $quote = $token;
914
915 1088
        while (++$this->last < $this->len) {
916
            if (
917 1088
                $this->last + 1 < $this->len
918
                && (
919 1084
                    ($this->str[$this->last] === $quote && $this->str[$this->last + 1] === $quote)
920 1088
                    || ($this->str[$this->last] === '\\' && $quote !== '`')
921
                )
922
            ) {
923 48
                $token .= $this->str[$this->last] . $this->str[++$this->last];
924
            } else {
925 1088
                if ($this->str[$this->last] === $quote) {
926 1080
                    break;
927
                }
928
929 1080
                $token .= $this->str[$this->last];
930
            }
931
        }
932
933 1088
        if ($this->last >= $this->len || $this->str[$this->last] !== $quote) {
934 28
            $this->error(
935 28
                sprintf(
936 28
                    Translator::gettext('Ending quote %1$s was expected.'),
937 28
                    $quote
938
                ),
939 28
                '',
940 28
                $this->last
941
            );
942
        } else {
943 1080
            $token .= $this->str[$this->last];
944
        }
945
946 1088
        return new Token($token, Token::TYPE_STRING, $flags);
947
    }
948
949
    /**
950
     * Parses a symbol.
951
     *
952
     * @return Token|null
953
     *
954
     * @throws LexerException
955
     */
956 2196
    public function parseSymbol()
957
    {
958 2196
        $token = $this->str[$this->last];
959 2196
        $flags = Context::isSymbol($token);
960
961 2196
        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...
962 2192
            return null;
963
        }
964
965 688
        if ($flags & Token::FLAG_SYMBOL_VARIABLE) {
966 148
            if ($this->last + 1 < $this->len && $this->str[++$this->last] === '@') {
967
                // This is a system variable (e.g. `@@hostname`).
968 8
                $token .= $this->str[$this->last++];
969 148
                $flags |= Token::FLAG_SYMBOL_SYSTEM;
970
            }
971 584
        } elseif ($flags & Token::FLAG_SYMBOL_PARAMETER) {
972 12
            if ($token !== '?' && $this->last + 1 < $this->len) {
973 12
                ++$this->last;
974
            }
975
        } else {
976 576
            $token = '';
977
        }
978
979 688
        $str = null;
980
981 688
        if ($this->last < $this->len) {
982 688
            $str = $this->parseString('`');
983
984 688
            if ($str === null) {
985 108
                $str = $this->parseUnknown();
986
987 108
                if ($str === null) {
988 12
                    $this->error('Variable name was expected.', $this->str[$this->last], $this->last);
989
                }
990
            }
991
        }
992
993 688
        if ($str !== null) {
994 680
            $token .= $str->token;
995
        }
996
997 688
        return new Token($token, Token::TYPE_SYMBOL, $flags);
998
    }
999
1000
    /**
1001
     * Parses unknown parts of the query.
1002
     *
1003
     * @return Token|null
1004
     */
1005 1648
    public function parseUnknown()
1006
    {
1007 1648
        $token = $this->str[$this->last];
1008 1648
        if (Context::isSeparator($token)) {
1009 20
            return null;
1010
        }
1011
1012 1644
        while (++$this->last < $this->len && ! Context::isSeparator($this->str[$this->last])) {
1013 1600
            $token .= $this->str[$this->last];
1014
1015
            // Test if end of token equals the current delimiter. If so, remove it from the token.
1016 1600
            if (str_ends_with($token, $this->delimiter)) {
1017 4
                $token = substr($token, 0, -$this->delimiterLen);
1018 4
                $this->last -= $this->delimiterLen - 1;
1019 4
                break;
1020
            }
1021
        }
1022
1023 1644
        --$this->last;
1024
1025 1644
        return new Token($token);
1026
    }
1027
1028
    /**
1029
     * Parses the delimiter of the query.
1030
     *
1031
     * @return Token|null
1032
     */
1033 2228
    public function parseDelimiter()
1034
    {
1035 2228
        $idx = 0;
1036
1037 2228
        while ($idx < $this->delimiterLen && $this->last + $idx < $this->len) {
1038 2228
            if ($this->delimiter[$idx] !== $this->str[$this->last + $idx]) {
1039 2228
                return null;
1040
            }
1041
1042 748
            ++$idx;
1043
        }
1044
1045 748
        $this->last += $this->delimiterLen - 1;
1046
1047 748
        return new Token($this->delimiter, Token::TYPE_DELIMITER);
1048
    }
1049
}
1050