Passed
Pull Request — master (#483)
by
unknown
02:48
created

CreateDefinition::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpMyAdmin\SqlParser\Components;
6
7
use PhpMyAdmin\SqlParser\Component;
8
use PhpMyAdmin\SqlParser\Context;
9
use PhpMyAdmin\SqlParser\Parser;
10
use PhpMyAdmin\SqlParser\Token;
11
use PhpMyAdmin\SqlParser\TokensList;
12
13
use function implode;
14
use function trim;
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 CreateDefinition implements Component
22
{
23
    /**
24
     * All field options.
25
     *
26
     * @var array<string, bool|int|array<int, int|string|array<string, bool>>>
27
     * @psalm-var array<string, (bool|positive-int|array{
28
     *   0: positive-int,
29
     *   1: ('var'|'var='|'expr'|'expr='),
30
     *   2?: array<string, bool>
31
     * })>
32
     */
33
    public static $fieldOptions = [
34
        // Tells the `OptionsArray` to not sort the options.
35
        // See the note below.
36
        '_UNSORTED' => true,
37
38
        'NOT NULL' => 1,
39
        'NULL' => 1,
40
        'DEFAULT' => [
41
            2,
42
            'expr',
43
            ['breakOnAlias' => true],
44
        ],
45
        /* Following are not according to grammar, but MySQL happily accepts
46
         * these at any location */
47
        'CHARSET' => [
48
            2,
49
            'var',
50
        ],
51
        'COLLATE' => [
52
            3,
53
            'var',
54
        ],
55
        'AUTO_INCREMENT' => 3,
56
        'KEY' => 4,
57
        'PRIMARY' => 4,
58
        'PRIMARY KEY' => 4,
59
        'UNIQUE' => 4,
60
        'UNIQUE KEY' => 4,
61
        'COMMENT' => [
62
            5,
63
            'var',
64
        ],
65
        'COLUMN_FORMAT' => [
66
            6,
67
            'var',
68
        ],
69
        'ON UPDATE' => [
70
            7,
71
            'expr',
72
        ],
73
74
        // Generated columns options.
75
        'GENERATED ALWAYS' => 8,
76
        'AS' => [
77
            9,
78
            'expr',
79
            ['parenthesesDelimited' => true],
80
        ],
81
        'VIRTUAL' => 10,
82
        'PERSISTENT' => 11,
83
        'STORED' => 11,
84
        'CHECK' => [
85
            12,
86
            'expr',
87
            ['parenthesesDelimited' => true],
88
        ],
89
        'INVISIBLE' => 13,
90
        'ENFORCED' => 14,
91
        'NOT' => 15,
92
        'COMPRESSED' => 16,
93
        // Common entries.
94
        //
95
        // NOTE: Some of the common options are not in the same order which
96
        // causes troubles when checking if the options are in the right order.
97
        // I should find a way to define multiple sets of options and make the
98
        // parser select the right set.
99
        //
100
        // 'UNIQUE'                        => 4,
101
        // 'UNIQUE KEY'                    => 4,
102
        // 'COMMENT'                       => [5, 'var'],
103
        // 'NOT NULL'                      => 1,
104
        // 'NULL'                          => 1,
105
        // 'PRIMARY'                       => 4,
106
        // 'PRIMARY KEY'                   => 4,
107
    ];
108
109
    /**
110
     * The name of the new column.
111
     *
112
     * @var string|null
113
     */
114
    public $name;
115
116
    /**
117
     * Whether this field is a constraint or not.
118
     *
119
     * @var bool|null
120
     */
121
    public $isConstraint;
122
123
    /**
124
     * The data type of thew new column.
125
     *
126
     * @var DataType|null
127
     */
128
    public $type;
129
130
    /**
131
     * The key.
132
     *
133
     * @var Key|null
134
     */
135
    public $key;
136
137
    /**
138
     * The table that is referenced.
139
     *
140
     * @var Reference|null
141
     */
142
    public $references;
143
144
    /**
145
     * The options of this field.
146
     *
147
     * @var OptionsArray|null
148
     */
149
    public $options;
150
151
    /**
152
     * @param string|null       $name         the name of the field
153
     * @param OptionsArray|null $options      the options of this field
154
     * @param DataType|Key|null $type         the data type of this field or the key
155
     * @param bool              $isConstraint whether this field is a constraint or not
156
     * @param Reference|null    $references   references
157
     */
158 118
    public function __construct(
159
        $name = null,
160
        $options = null,
161
        $type = null,
162
        $isConstraint = false,
163
        $references = null
164
    ) {
165 118
        $this->name = $name;
166 118
        $this->options = $options;
167 118
        if ($type instanceof DataType) {
168 2
            $this->type = $type;
169 118
        } elseif ($type instanceof Key) {
170 2
            $this->key = $type;
171 2
            $this->isConstraint = $isConstraint;
172 2
            $this->references = $references;
173
        }
174
    }
175
176
    /**
177
     * @param Parser               $parser  the parser that serves as context
178
     * @param TokensList           $list    the list of tokens that are being parsed
179
     * @param array<string, mixed> $options parameters for parsing
180
     *
181
     * @return CreateDefinition[]
182
     */
183 118
    public static function parse(Parser $parser, TokensList $list, array $options = [])
184
    {
185 118
        $ret = [];
186
187 118
        $expr = new static();
188
189
        /**
190
         * The state of the parser.
191
         *
192
         * Below are the states of the parser.
193
         *
194
         *      0 -----------------------[ ( ]------------------------> 1
195
         *
196
         *      1 --------------------[ CONSTRAINT ]------------------> 1
197
         *      1 -----------------------[ key ]----------------------> 2
198
         *      1 -------------[ constraint / column name ]-----------> 2
199
         *
200
         *      2 --------------------[ data type ]-------------------> 3
201
         *
202
         *      3 ---------------------[ options ]--------------------> 4
203
         *
204
         *      4 --------------------[ REFERENCES ]------------------> 4
205
         *
206
         *      5 ------------------------[ , ]-----------------------> 1
207
         *      5 ------------------------[ ) ]-----------------------> 6 (-1)
208
         *
209
         * @var int
210
         */
211 118
        $state = 0;
212
213 118
        for (; $list->idx < $list->count; ++$list->idx) {
214
            /**
215
             * Token parsed at this moment.
216
             */
217 118
            $token = $list->tokens[$list->idx];
218
219
            // End of statement.
220 118
            if ($token->type === Token::TYPE_DELIMITER) {
221 4
                break;
222
            }
223
224
            // Skipping whitespaces and comments.
225 116
            if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
226 110
                continue;
227
            }
228
229 116
            if ($state === 0) {
230 116
                if (($token->type !== Token::TYPE_OPERATOR) || ($token->value !== '(')) {
231 2
                    $parser->error('An opening bracket was expected.', $token);
232
233 2
                    break;
234
                }
235
236 114
                $state = 1;
237 114
            } elseif ($state === 1) {
238 114
                if ($token->type === Token::TYPE_KEYWORD && $token->keyword === 'CONSTRAINT') {
239 18
                    $expr->isConstraint = true;
240 114
                } elseif (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_KEY)) {
241 42
                    $expr->key = Key::parse($parser, $list);
242 42
                    $state = 4;
243 114
                } elseif ($token->type === Token::TYPE_SYMBOL || $token->type === Token::TYPE_NONE) {
244 108
                    $expr->name = $token->value;
245 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...
246 108
                        $state = 2;
247
                    }
248 14
                } elseif ($token->type === Token::TYPE_KEYWORD) {
249 12
                    if ($token->flags & Token::FLAG_KEYWORD_RESERVED) {
250
                        // Reserved keywords can't be used
251
                        // as field names without backquotes
252 2
                        $parser->error(
253 2
                            'A symbol name was expected! '
254 2
                            . 'A reserved keyword can not be used '
255 2
                            . 'as a column name without backquotes.',
256 2
                            $token
257 2
                        );
258
259 2
                        return $ret;
260
                    }
261
262
                    // Non-reserved keywords are allowed without backquotes
263 10
                    $expr->name = $token->value;
264 10
                    $state = 2;
265
                } else {
266 2
                    $parser->error('A symbol name was expected!', $token);
267
268 112
                    return $ret;
269
                }
270 110
            } elseif ($state === 2) {
271 110
                $expr->type = DataType::parse($parser, $list);
272 110
                $state = 3;
273 110
            } elseif ($state === 3) {
274 110
                $expr->options = OptionsArray::parse($parser, $list, static::$fieldOptions);
275 110
                $state = 4;
276 110
            } elseif ($state === 4) {
277 110
                if ($token->type === Token::TYPE_KEYWORD && $token->keyword === 'REFERENCES') {
278 16
                    ++$list->idx; // Skipping keyword 'REFERENCES'.
279 16
                    $expr->references = Reference::parse($parser, $list);
280
                } else {
281 110
                    --$list->idx;
282
                }
283
284 110
                $state = 5;
285 110
            } elseif ($state === 5) {
286 110
                if (! empty($expr->type) || ! empty($expr->key)) {
287 110
                    $ret[] = $expr;
288
                }
289
290 110
                $expr = new static();
291 110
                if ($token->value === ',') {
292 76
                    $state = 1;
293 108
                } elseif ($token->value === ')') {
294 106
                    $state = 6;
295 106
                    ++$list->idx;
296 106
                    break;
297
                } else {
298 2
                    $parser->error('A comma or a closing bracket was expected.', $token);
299 2
                    $state = 0;
300 2
                    break;
301
                }
302
            }
303
        }
304
305
        // Last iteration was not saved.
306 114
        if (! empty($expr->type) || ! empty($expr->key)) {
307 2
            $ret[] = $expr;
308
        }
309
310 114
        if (($state !== 0) && ($state !== 6)) {
311 2
            $parser->error('A closing bracket was expected.', $list->tokens[$list->idx - 1]);
312
        }
313
314 114
        --$list->idx;
315
316 114
        return $ret;
317
    }
318
319
    /**
320
     * @param CreateDefinition $component the component to be built
321
     */
322 36
    public static function build($component): string
323
    {
324 36
        $tmp = '';
325
326 36
        if ($component->isConstraint) {
327 4
            $tmp .= 'CONSTRAINT ';
328
        }
329
330 36
        if (isset($component->name) && ($component->name !== '')) {
331 34
            $tmp .= Context::escape($component->name) . ' ';
0 ignored issues
show
Bug introduced by
It seems like $component->name can also be of type null; however, parameter $str of PhpMyAdmin\SqlParser\Context::escape() 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

331
            $tmp .= Context::escape(/** @scrutinizer ignore-type */ $component->name) . ' ';
Loading history...
332
        }
333
334 36
        if (! empty($component->type)) {
335 30
            $component->type->lowercase = true;
336 30
            $tmp .= DataType::build($component->type) . ' ';
337
        }
338
339 36
        if (! empty($component->key)) {
340 12
            $tmp .= $component->key . ' ';
341
        }
342
343 36
        if (! empty($component->references)) {
344 4
            $tmp .= 'REFERENCES ' . $component->references . ' ';
345
        }
346
347 36
        $tmp .= $component->options;
348
349 36
        return trim($tmp);
350
    }
351
352
    /**
353
     * @param CreateDefinition[] $component the component to be built
354
     */
355 26
    public static function buildAll(array $component): string
356
    {
357 26
        return "(\n  " . implode(",\n  ", $component) . "\n)";
358
    }
359
360 28
    public function __toString(): string
361
    {
362 28
        return static::build($this);
363
    }
364
}
365