Passed
Push — master ( b16987...8b6d77 )
by Maurício
03:49 queued 13s
created

CreateDefinitions::parse()   D

Complexity

Conditions 31
Paths 30

Size

Total Lines 132
Code Lines 70

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 68
CRAP Score 31

Importance

Changes 0
Metric Value
cc 31
eloc 70
nc 30
nop 3
dl 0
loc 132
ccs 68
cts 68
cp 1
crap 31
rs 4.1666
c 0
b 0
f 0

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\Parsers;
6
7
use PhpMyAdmin\SqlParser\Components\CreateDefinition;
8
use PhpMyAdmin\SqlParser\Parseable;
9
use PhpMyAdmin\SqlParser\Parser;
10
use PhpMyAdmin\SqlParser\Token;
11
use PhpMyAdmin\SqlParser\TokensList;
12
use PhpMyAdmin\SqlParser\TokenType;
13
14
use function implode;
15
16
/**
17
 * Parses the create definition of a column or a key.
18
 *
19
 * Used for parsing `CREATE TABLE` statement.
20
 */
21
final class CreateDefinitions implements Parseable
22
{
23
    /**
24
     * All field options.
25
     */
26
    private const FIELD_OPTIONS = [
27
        // Tells the `OptionsArray` to not sort the options.
28
        // See the note below.
29
        '_UNSORTED' => true,
30
31
        'NOT NULL' => 1,
32
        'NULL' => 1,
33
        'DEFAULT' => [
34
            2,
35
            'expr',
36
            ['breakOnAlias' => true],
37
        ],
38
        /* Following are not according to grammar, but MySQL happily accepts
39
         * these at any location */
40
        'CHARSET' => [
41
            2,
42
            'var',
43
        ],
44
        'COLLATE' => [
45
            3,
46
            'var',
47
        ],
48
        'AUTO_INCREMENT' => 3,
49
        'KEY' => 4,
50
        'PRIMARY' => 4,
51
        'PRIMARY KEY' => 4,
52
        'UNIQUE' => 4,
53
        'UNIQUE KEY' => 4,
54
        'COMMENT' => [
55
            5,
56
            'var',
57
        ],
58
        'COLUMN_FORMAT' => [
59
            6,
60
            'var',
61
        ],
62
        'ON UPDATE' => [
63
            7,
64
            'expr',
65
        ],
66
67
        // Generated columns options.
68
        'GENERATED ALWAYS' => 8,
69
        'AS' => [
70
            9,
71
            'expr',
72
            ['parenthesesDelimited' => true],
73
        ],
74
        'VIRTUAL' => 10,
75
        'PERSISTENT' => 11,
76
        'STORED' => 11,
77
        'CHECK' => [
78
            12,
79
            'expr',
80
            ['parenthesesDelimited' => true],
81
        ],
82
        'INVISIBLE' => 13,
83
        'ENFORCED' => 14,
84
        'NOT' => 15,
85
        'COMPRESSED' => 16,
86
        // Common entries.
87
        //
88
        // NOTE: Some of the common options are not in the same order which
89
        // causes troubles when checking if the options are in the right order.
90
        // I should find a way to define multiple sets of options and make the
91
        // parser select the right set.
92
        //
93
        // 'UNIQUE'                        => 4,
94
        // 'UNIQUE KEY'                    => 4,
95
        // 'COMMENT'                       => [5, 'var'],
96
        // 'NOT NULL'                      => 1,
97
        // 'NULL'                          => 1,
98
        // 'PRIMARY'                       => 4,
99
        // 'PRIMARY KEY'                   => 4,
100
    ];
101
102
    /**
103
     * @param Parser               $parser  the parser that serves as context
104
     * @param TokensList           $list    the list of tokens that are being parsed
105
     * @param array<string, mixed> $options parameters for parsing
106
     *
107
     * @return CreateDefinition[]
108
     */
109 118
    public static function parse(Parser $parser, TokensList $list, array $options = []): array
110
    {
111 118
        $ret = [];
112
113 118
        $expr = new CreateDefinition();
114
115
        /**
116
         * The state of the parser.
117
         *
118
         * Below are the states of the parser.
119
         *
120
         *      0 -----------------------[ ( ]------------------------> 1
121
         *
122
         *      1 --------------------[ CONSTRAINT ]------------------> 1
123
         *      1 -----------------------[ key ]----------------------> 2
124
         *      1 -------------[ constraint / column name ]-----------> 2
125
         *
126
         *      2 --------------------[ data type ]-------------------> 3
127
         *
128
         *      3 ---------------------[ options ]--------------------> 4
129
         *
130
         *      4 --------------------[ REFERENCES ]------------------> 4
131
         *
132
         *      5 ------------------------[ , ]-----------------------> 1
133
         *      5 ------------------------[ ) ]-----------------------> 6 (-1)
134
         */
135 118
        $state = 0;
136
137 118
        for (; $list->idx < $list->count; ++$list->idx) {
138
            /**
139
             * Token parsed at this moment.
140
             */
141 118
            $token = $list->tokens[$list->idx];
142
143
            // End of statement.
144 118
            if ($token->type === TokenType::Delimiter) {
145 4
                break;
146
            }
147
148
            // Skipping whitespaces and comments.
149 116
            if (($token->type === TokenType::Whitespace) || ($token->type === TokenType::Comment)) {
150 110
                continue;
151
            }
152
153 116
            if ($state === 0) {
154 116
                if (($token->type !== TokenType::Operator) || ($token->value !== '(')) {
155 2
                    $parser->error('An opening bracket was expected.', $token);
156
157 2
                    break;
158
                }
159
160 114
                $state = 1;
161 114
            } elseif ($state === 1) {
162 114
                if ($token->type === TokenType::Keyword && $token->keyword === 'CONSTRAINT') {
163 18
                    $expr->isConstraint = true;
164 114
                } elseif (($token->type === TokenType::Keyword) && ($token->flags & Token::FLAG_KEYWORD_KEY)) {
165 42
                    $expr->key = Keys::parse($parser, $list);
166 42
                    $state = 4;
167 114
                } elseif ($token->type === TokenType::Symbol || $token->type === TokenType::None) {
168 108
                    $expr->name = $token->value;
169 108
                    if (! $expr->isConstraint) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $expr->isConstraint of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
170 108
                        $state = 2;
171
                    }
172 14
                } elseif ($token->type === TokenType::Keyword) {
173 12
                    if ($token->flags & Token::FLAG_KEYWORD_RESERVED) {
174
                        // Reserved keywords can't be used
175
                        // as field names without backquotes
176 2
                        $parser->error(
177 2
                            'A symbol name was expected! '
178 2
                            . 'A reserved keyword can not be used '
179 2
                            . 'as a column name without backquotes.',
180 2
                            $token,
181 2
                        );
182
183 2
                        return $ret;
184
                    }
185
186
                    // Non-reserved keywords are allowed without backquotes
187 10
                    $expr->name = $token->value;
188 10
                    $state = 2;
189
                } else {
190 2
                    $parser->error('A symbol name was expected!', $token);
191
192 2
                    return $ret;
193
                }
194 110
            } elseif ($state === 2) {
195 110
                $expr->type = DataTypes::parse($parser, $list);
196 110
                $state = 3;
197 110
            } elseif ($state === 3) {
198 110
                $expr->options = OptionsArrays::parse($parser, $list, self::FIELD_OPTIONS);
199 110
                $state = 4;
200 110
            } elseif ($state === 4) {
201 110
                if ($token->type === TokenType::Keyword && $token->keyword === 'REFERENCES') {
202 16
                    ++$list->idx; // Skipping keyword 'REFERENCES'.
203 16
                    $expr->references = References::parse($parser, $list);
204
                } else {
205 110
                    --$list->idx;
206
                }
207
208 110
                $state = 5;
209
            } else {
210 110
                if (! empty($expr->type) || ! empty($expr->key)) {
211 110
                    $ret[] = $expr;
212
                }
213
214 110
                $expr = new CreateDefinition();
215 110
                if ($token->value === ',') {
216 76
                    $state = 1;
217 108
                } elseif ($token->value === ')') {
218 106
                    $state = 6;
219 106
                    ++$list->idx;
220 106
                    break;
221
                } else {
222 2
                    $parser->error('A comma or a closing bracket was expected.', $token);
223 2
                    $state = 0;
224 2
                    break;
225
                }
226
            }
227
        }
228
229
        // Last iteration was not saved.
230 114
        if (! empty($expr->type) || ! empty($expr->key)) {
231 2
            $ret[] = $expr;
232
        }
233
234 114
        if (($state !== 0) && ($state !== 6)) {
235 2
            $parser->error('A closing bracket was expected.', $list->tokens[$list->idx - 1]);
236
        }
237
238 114
        --$list->idx;
239
240 114
        return $ret;
241
    }
242
243
    /** @param CreateDefinition[] $component the component to be built */
244 26
    public static function buildAll(array $component): string
245
    {
246 26
        return "(\n  " . implode(",\n  ", $component) . "\n)";
247
    }
248
}
249