Passed
Push — master ( 4cd530...dde1fc )
by William
02:46 queued 11s
created

AlterOperation   A

Complexity

Total Complexity 39

Size/Duplication

Total Lines 369
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 1 Features 0
Metric Value
eloc 159
c 4
b 1
f 0
dl 0
loc 369
ccs 82
cts 82
cp 1
rs 9.28
wmc 39

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A checkIfColumnDefinitionKeyword() 0 17 1
D parse() 0 151 32
A checkIfTokenQuotedSymbol() 0 3 2
A build() 0 10 3
1
<?php
2
/**
3
 * Parses an alter operation.
4
 */
5
6
declare(strict_types=1);
7
8
namespace PhpMyAdmin\SqlParser\Components;
9
10
use PhpMyAdmin\SqlParser\Component;
11
use PhpMyAdmin\SqlParser\Parser;
12
use PhpMyAdmin\SqlParser\Token;
13
use PhpMyAdmin\SqlParser\TokensList;
14
15
use function array_key_exists;
16
use function in_array;
17
use function is_numeric;
18
use function is_string;
19
20
/**
21
 * Parses an alter operation.
22
 */
23
class AlterOperation extends Component
24
{
25
    /**
26
     * All database options.
27
     *
28
     * @var array
29
     */
30
    public static $DB_OPTIONS = [
31
        'CHARACTER SET' => [
32
            1,
33
            'var',
34
        ],
35
        'CHARSET' => [
36
            1,
37
            'var',
38
        ],
39
        'DEFAULT CHARACTER SET' => [
40
            1,
41
            'var',
42
        ],
43
        'DEFAULT CHARSET' => [
44
            1,
45
            'var',
46
        ],
47
        'UPGRADE' => [
48
            1,
49
            'var',
50
        ],
51
        'COLLATE' => [
52
            2,
53
            'var',
54
        ],
55
        'DEFAULT COLLATE' => [
56
            2,
57
            'var',
58
        ],
59
    ];
60
61
    /**
62
     * All table options.
63
     *
64
     * @var array
65
     */
66
    public static $TABLE_OPTIONS = [
67
        'ENGINE' => [
68
            1,
69
            'var=',
70
        ],
71
        'AUTO_INCREMENT' => [
72
            1,
73
            'var=',
74
        ],
75
        'AVG_ROW_LENGTH' => [
76
            1,
77
            'var',
78
        ],
79
        'MAX_ROWS' => [
80
            1,
81
            'var',
82
        ],
83
        'ROW_FORMAT' => [
84
            1,
85
            'var',
86
        ],
87
        'COMMENT' => [
88
            1,
89
            'var',
90
        ],
91
        'ADD' => 1,
92
        'ALTER' => 1,
93
        'ANALYZE' => 1,
94
        'CHANGE' => 1,
95
        'CHARSET' => 1,
96
        'CHECK' => 1,
97
        'COALESCE' => 1,
98
        'CONVERT' => 1,
99
        'DEFAULT CHARSET' => 1,
100
        'DISABLE' => 1,
101
        'DISCARD' => 1,
102
        'DROP' => 1,
103
        'ENABLE' => 1,
104
        'IMPORT' => 1,
105
        'MODIFY' => 1,
106
        'OPTIMIZE' => 1,
107
        'ORDER' => 1,
108
        'PARTITION' => 1,
109
        'REBUILD' => 1,
110
        'REMOVE' => 1,
111
        'RENAME' => 1,
112
        'REORGANIZE' => 1,
113
        'REPAIR' => 1,
114
        'UPGRADE' => 1,
115
116
        'COLUMN' => 2,
117
        'CONSTRAINT' => 2,
118
        'DEFAULT' => 2,
119
        'TO' => 2,
120
        'BY' => 2,
121
        'FOREIGN' => 2,
122
        'FULLTEXT' => 2,
123
        'KEY' => 2,
124
        'KEYS' => 2,
125
        'PARTITIONING' => 2,
126
        'PRIMARY KEY' => 2,
127
        'SPATIAL' => 2,
128
        'TABLESPACE' => 2,
129
        'INDEX' => 2,
130
131
        'CHARACTER SET' => 3,
132
    ];
133
134
    /**
135
     * All view options.
136
     *
137
     * @var array
138
     */
139
    public static $VIEW_OPTIONS = ['AS' => 1];
140
141
    /**
142
     * Options of this operation.
143
     *
144
     * @var OptionsArray
145
     */
146
    public $options;
147
148
    /**
149
     * The altered field.
150
     *
151
     * @var Expression
152
     */
153
    public $field;
154
155
    /**
156
     * Unparsed tokens.
157
     *
158
     * @var Token[]|string
159
     */
160
    public $unknown = [];
161
162
    /**
163
     * @param OptionsArray $options options of alter operation
164
     * @param Expression   $field   altered field
165
     * @param array        $unknown unparsed tokens found at the end of operation
166
     */
167 128
    public function __construct(
168
        $options = null,
169
        $field = null,
170
        $unknown = []
171
    ) {
172 128
        $this->options = $options;
173 128
        $this->field = $field;
174 128
        $this->unknown = $unknown;
175 128
    }
176
177
    /**
178
     * @param Parser     $parser  the parser that serves as context
179
     * @param TokensList $list    the list of tokens that are being parsed
180
     * @param array      $options parameters for parsing
181
     *
182
     * @return AlterOperation
183
     */
184 128
    public static function parse(Parser $parser, TokensList $list, array $options = [])
185
    {
186 128
        $ret = new static();
187
188
        /**
189
         * Counts brackets.
190
         *
191
         * @var int
192
         */
193 128
        $brackets = 0;
194
195
        /**
196
         * The state of the parser.
197
         *
198
         * Below are the states of the parser.
199
         *
200
         *      0 ---------------------[ options ]---------------------> 1
201
         *
202
         *      1 ----------------------[ field ]----------------------> 2
203
         *
204
         *      2 -------------------------[ , ]-----------------------> 0
205
         *
206
         * @var int
207
         */
208 128
        $state = 0;
209
210 128
        for (; $list->idx < $list->count; ++$list->idx) {
211
            /**
212
             * Token parsed at this moment.
213
             *
214
             * @var Token
215
             */
216 128
            $token = $list->tokens[$list->idx];
217
218
            // End of statement.
219 128
            if ($token->type === Token::TYPE_DELIMITER) {
220 104
                break;
221
            }
222
223
            // Skipping comments.
224 128
            if ($token->type === Token::TYPE_COMMENT) {
225 4
                continue;
226
            }
227
228
            // Skipping whitespaces.
229 128
            if ($token->type === Token::TYPE_WHITESPACE) {
230 68
                if ($state === 2) {
231
                    // When parsing the unknown part, the whitespaces are
232
                    // included to not break anything.
233 68
                    $ret->unknown[] = $token;
234
                }
235
236 68
                continue;
237
            }
238
239 128
            if ($state === 0) {
240 128
                $ret->options = OptionsArray::parse($parser, $list, $options);
241
242 128
                if ($ret->options->has('AS')) {
243 4
                    for (; $list->idx < $list->count; ++$list->idx) {
244 4
                        if ($list->tokens[$list->idx]->type === Token::TYPE_DELIMITER) {
245 4
                            break;
246
                        }
247
248 4
                        $ret->unknown[] = $list->tokens[$list->idx];
249
                    }
250
251 4
                    break;
252
                }
253
254 124
                $state = 1;
255 112
            } elseif ($state === 1) {
256 112
                $ret->field = Expression::parse(
257 112
                    $parser,
258 112
                    $list,
259
                    [
260 112
                        'breakOnAlias' => true,
261
                        'parseField' => 'column',
262
                    ]
263
                );
264 112
                if ($ret->field === null) {
265
                    // No field was read. We go back one token so the next
266
                    // iteration will parse the same token, but in state 2.
267 24
                    --$list->idx;
268
                }
269
270 112
                $state = 2;
271 96
            } elseif ($state === 2) {
272 96
                $arrayKey = '';
273 96
                if (is_string($token->value) || is_numeric($token->value)) {
274 96
                    $arrayKey = $token->value;
275
                } else {
276 4
                    $arrayKey = $token->token;
277
                }
278
279 96
                if ($token->type === Token::TYPE_OPERATOR) {
280 60
                    if ($token->value === '(') {
281 44
                        ++$brackets;
282 60
                    } elseif ($token->value === ')') {
283 44
                        --$brackets;
284 32
                    } elseif (($token->value === ',') && ($brackets === 0)) {
285 60
                        break;
286
                    }
287 96
                } elseif (! self::checkIfTokenQuotedSymbol($token)) {
288 84
                    if (! empty(Parser::$STATEMENT_PARSERS[$token->value])) {
289
                        // We want to get the next non-comment and non-space token after $token
290
                        // therefore, the first getNext call will start with the current $idx which's $token,
291
                        // will return it and increase $idx by 1, which's not guaranteed to be non-comment
292
                        // and non-space, that's why we're calling getNext again.
293
294 24
                        $list->getNext();
295 24
                        $nextToken = $list->getNext();
296
297 24
                        if ($token->value === 'SET' && $nextToken !== null && $nextToken->value === '(') {
298
                            // To avoid adding the tokens between the SET() parentheses to the unknown tokens
299 8
                            $list->getNextOfTypeAndValue(Token::TYPE_OPERATOR, ')');
300 16
                        } elseif ($token->value === 'SET' && $nextToken !== null && $nextToken->value === 'DEFAULT') {
301
                            // to avoid adding the `DEFAULT` token to the unknown tokens.
302 8
                            ++$list->idx;
303
                        } else {
304
                            // We have reached the end of ALTER operation and suddenly found
305
                            // a start to new statement, but have not find a delimiter between them
306 8
                            $parser->error(
307 8
                                'A new statement was found, but no delimiter between it and the previous one.',
308 2
                                $token
309
                            );
310 24
                            break;
311
                        }
312
                    } elseif (
313 38
                        (array_key_exists($arrayKey, self::$DB_OPTIONS)
314 76
                        || array_key_exists($arrayKey, self::$TABLE_OPTIONS))
315 76
                        && ! self::checkIfColumnDefinitionKeyword($arrayKey)
316
                    ) {
317
                        // This alter operation has finished, which means a comma
318
                        // was missing before start of new alter operation
319 8
                        $parser->error('Missing comma before start of a new alter operation.', $token);
320 8
                        break;
321
                    }
322
                }
323
324 96
                $ret->unknown[] = $token;
325
            }
326
        }
327
328 128
        if ($ret->options->isEmpty()) {
329 4
            $parser->error('Unrecognized alter operation.', $list->tokens[$list->idx]);
330
        }
331
332 128
        --$list->idx;
333
334 128
        return $ret;
335
    }
336
337
    /**
338
     * @param AlterOperation $component the component to be built
339
     * @param array          $options   parameters for building
340
     *
341
     * @return string
342
     */
343 4
    public static function build($component, array $options = [])
344
    {
345 4
        $ret = $component->options . ' ';
346 4
        if (isset($component->field) && ($component->field !== '')) {
347 4
            $ret .= $component->field . ' ';
348
        }
349
350 4
        $ret .= TokensList::build($component->unknown);
351
352 4
        return $ret;
353
    }
354
355
    /**
356
     * Check if token's value is one of the common keywords
357
     * between column and table alteration
358
     *
359
     * @param string $tokenValue Value of current token
360
     *
361
     * @return bool
362
     */
363 56
    private static function checkIfColumnDefinitionKeyword($tokenValue)
364
    {
365 14
        $commonOptions = [
366 42
            'AUTO_INCREMENT',
367
            'COMMENT',
368
            'DEFAULT',
369
            'CHARACTER SET',
370
            'COLLATE',
371
            'PRIMARY',
372
            'UNIQUE',
373
            'PRIMARY KEY',
374
            'UNIQUE KEY',
375
        ];
376
377
        // Since these options can be used for
378
        // both table as well as a specific column in the table
379 56
        return in_array($tokenValue, $commonOptions);
380
    }
381
382
    /**
383
     * Check if token is symbol and quoted with backtick
384
     *
385
     * @param Token $token token to check
386
     *
387
     * @return bool
388
     */
389 96
    private static function checkIfTokenQuotedSymbol($token)
390
    {
391 96
        return $token->type === Token::TYPE_SYMBOL && $token->flags === Token::FLAG_SYMBOL_BACKTICK;
392
    }
393
}
394