Passed
Pull Request — master (#535)
by
unknown
02:55
created

CreateDefinitions::parse()   D

Complexity

Conditions 32
Paths 30

Size

Total Lines 134
Code Lines 70

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 69
CRAP Score 32

Importance

Changes 0
Metric Value
cc 32
eloc 70
c 0
b 0
f 0
nc 30
nop 3
dl 0
loc 134
rs 4.1666
ccs 69
cts 69
cp 1
crap 32

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\Components\Parsers;
6
7
use PhpMyAdmin\SqlParser\Components\CreateDefinition;
8
use PhpMyAdmin\SqlParser\Components\DataType;
9
use PhpMyAdmin\SqlParser\Components\Key;
10
use PhpMyAdmin\SqlParser\Components\OptionsArray;
11
use PhpMyAdmin\SqlParser\Components\Reference;
12
use PhpMyAdmin\SqlParser\Parseable;
13
use PhpMyAdmin\SqlParser\Parser;
14
use PhpMyAdmin\SqlParser\Token;
15
use PhpMyAdmin\SqlParser\TokensList;
16
use PhpMyAdmin\SqlParser\TokenType;
17
18
use function implode;
19
20
/**
21
 * Parses the create definition of a column or a key.
22
 *
23
 * Used for parsing `CREATE TABLE` statement.
24
 */
25
final class CreateDefinitions implements Parseable
26
{
27
    /**
28
     * All field options.
29
     */
30
    private const FIELD_OPTIONS = [
31
        // Tells the `OptionsArray` to not sort the options.
32
        // See the note below.
33
        '_UNSORTED' => true,
34
35
        'NOT NULL' => 1,
36
        'NULL' => 1,
37
        'DEFAULT' => [
38
            2,
39
            'expr',
40
            ['breakOnAlias' => true],
41
        ],
42
        /* Following are not according to grammar, but MySQL happily accepts
43
         * these at any location */
44
        'CHARSET' => [
45
            2,
46
            'var',
47
        ],
48
        'COLLATE' => [
49
            3,
50
            'var',
51
        ],
52
        'AUTO_INCREMENT' => 3,
53
        'KEY' => 4,
54
        'PRIMARY' => 4,
55
        'PRIMARY KEY' => 4,
56
        'UNIQUE' => 4,
57
        'UNIQUE KEY' => 4,
58
        'COMMENT' => [
59
            5,
60
            'var',
61
        ],
62
        'COLUMN_FORMAT' => [
63
            6,
64
            'var',
65
        ],
66
        'ON UPDATE' => [
67
            7,
68
            'expr',
69
        ],
70
71
        // Generated columns options.
72
        'GENERATED ALWAYS' => 8,
73
        'AS' => [
74
            9,
75
            'expr',
76
            ['parenthesesDelimited' => true],
77
        ],
78
        'VIRTUAL' => 10,
79
        'PERSISTENT' => 11,
80
        'STORED' => 11,
81
        'CHECK' => [
82
            12,
83
            'expr',
84
            ['parenthesesDelimited' => true],
85
        ],
86
        'INVISIBLE' => 13,
87
        'ENFORCED' => 14,
88
        'NOT' => 15,
89
        'COMPRESSED' => 16,
90
        // Common entries.
91
        //
92
        // NOTE: Some of the common options are not in the same order which
93
        // causes troubles when checking if the options are in the right order.
94
        // I should find a way to define multiple sets of options and make the
95
        // parser select the right set.
96
        //
97
        // 'UNIQUE'                        => 4,
98
        // 'UNIQUE KEY'                    => 4,
99
        // 'COMMENT'                       => [5, 'var'],
100
        // 'NOT NULL'                      => 1,
101
        // 'NULL'                          => 1,
102
        // 'PRIMARY'                       => 4,
103
        // 'PRIMARY KEY'                   => 4,
104
    ];
105
106
    /**
107
     * @param Parser               $parser  the parser that serves as context
108
     * @param TokensList           $list    the list of tokens that are being parsed
109
     * @param array<string, mixed> $options parameters for parsing
110
     *
111
     * @return CreateDefinition[]
112
     */
113 118
    public static function parse(Parser $parser, TokensList $list, array $options = []): array
114
    {
115 118
        $ret = [];
116
117 118
        $expr = new CreateDefinition();
118
119
        /**
120
         * The state of the parser.
121
         *
122
         * Below are the states of the parser.
123
         *
124
         *      0 -----------------------[ ( ]------------------------> 1
125
         *
126
         *      1 --------------------[ CONSTRAINT ]------------------> 1
127
         *      1 -----------------------[ key ]----------------------> 2
128
         *      1 -------------[ constraint / column name ]-----------> 2
129
         *
130
         *      2 --------------------[ data type ]-------------------> 3
131
         *
132
         *      3 ---------------------[ options ]--------------------> 4
133
         *
134
         *      4 --------------------[ REFERENCES ]------------------> 4
135
         *
136
         *      5 ------------------------[ , ]-----------------------> 1
137
         *      5 ------------------------[ ) ]-----------------------> 6 (-1)
138
         *
139
         * @var int
140
         */
141 118
        $state = 0;
142
143 118
        for (; $list->idx < $list->count; ++$list->idx) {
144
            /**
145
             * Token parsed at this moment.
146
             */
147 118
            $token = $list->tokens[$list->idx];
148
149
            // End of statement.
150 118
            if ($token->type === TokenType::Delimiter) {
151 4
                break;
152
            }
153
154
            // Skipping whitespaces and comments.
155 116
            if (($token->type === TokenType::Whitespace) || ($token->type === TokenType::Comment)) {
156 110
                continue;
157
            }
158
159 116
            if ($state === 0) {
160 116
                if (($token->type !== TokenType::Operator) || ($token->value !== '(')) {
161 2
                    $parser->error('An opening bracket was expected.', $token);
162
163 2
                    break;
164
                }
165
166 114
                $state = 1;
167 114
            } elseif ($state === 1) {
168 114
                if ($token->type === TokenType::Keyword && $token->keyword === 'CONSTRAINT') {
169 18
                    $expr->isConstraint = true;
170 114
                } elseif (($token->type === TokenType::Keyword) && ($token->flags & Token::FLAG_KEYWORD_KEY)) {
171 42
                    $expr->key = Key::parse($parser, $list);
172 42
                    $state = 4;
173 114
                } elseif ($token->type === TokenType::Symbol || $token->type === TokenType::None) {
174 108
                    $expr->name = $token->value;
175 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...
176 108
                        $state = 2;
177
                    }
178 14
                } elseif ($token->type === TokenType::Keyword) {
179 12
                    if ($token->flags & Token::FLAG_KEYWORD_RESERVED) {
180
                        // Reserved keywords can't be used
181
                        // as field names without backquotes
182 2
                        $parser->error(
183 2
                            'A symbol name was expected! '
184 2
                            . 'A reserved keyword can not be used '
185 2
                            . 'as a column name without backquotes.',
186 2
                            $token,
187 2
                        );
188
189 2
                        return $ret;
190
                    }
191
192
                    // Non-reserved keywords are allowed without backquotes
193 10
                    $expr->name = $token->value;
194 10
                    $state = 2;
195
                } else {
196 2
                    $parser->error('A symbol name was expected!', $token);
197
198 57
                    return $ret;
199
                }
200 110
            } elseif ($state === 2) {
201 110
                $expr->type = DataType::parse($parser, $list);
202 110
                $state = 3;
203 110
            } elseif ($state === 3) {
204 110
                $expr->options = OptionsArray::parse($parser, $list, self::FIELD_OPTIONS);
205 110
                $state = 4;
206 110
            } elseif ($state === 4) {
207 110
                if ($token->type === TokenType::Keyword && $token->keyword === 'REFERENCES') {
208 16
                    ++$list->idx; // Skipping keyword 'REFERENCES'.
209 16
                    $expr->references = Reference::parse($parser, $list);
210
                } else {
211 110
                    --$list->idx;
212
                }
213
214 110
                $state = 5;
215 110
            } elseif ($state === 5) {
216 110
                if (! empty($expr->type) || ! empty($expr->key)) {
217 110
                    $ret[] = $expr;
218
                }
219
220 110
                $expr = new CreateDefinition();
221 110
                if ($token->value === ',') {
222 76
                    $state = 1;
223 108
                } elseif ($token->value === ')') {
224 106
                    $state = 6;
225 106
                    ++$list->idx;
226 106
                    break;
227
                } else {
228 2
                    $parser->error('A comma or a closing bracket was expected.', $token);
229 2
                    $state = 0;
230 2
                    break;
231
                }
232
            }
233
        }
234
235
        // Last iteration was not saved.
236 114
        if (! empty($expr->type) || ! empty($expr->key)) {
237 2
            $ret[] = $expr;
238
        }
239
240 114
        if (($state !== 0) && ($state !== 6)) {
241 2
            $parser->error('A closing bracket was expected.', $list->tokens[$list->idx - 1]);
242
        }
243
244 114
        --$list->idx;
245
246 114
        return $ret;
247
    }
248
249
    /** @param CreateDefinition[] $component the component to be built */
250 26
    public static function buildAll(array $component): string
251
    {
252 26
        return "(\n  " . implode(",\n  ", $component) . "\n)";
253
    }
254
}
255