Passed
Push — master ( 6c3f09...c54108 )
by William
03:43
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 is_array;
15
use function trim;
16
17
/**
18
 * Parses the create definition of a column or a key.
19
 *
20
 * Used for parsing `CREATE TABLE` statement.
21
 */
22
final class CreateDefinition implements Component
23
{
24
    /**
25
     * All field options.
26
     *
27
     * @var array<string, bool|int|array<int, int|string|array<string, bool>>>
28
     * @psalm-var array<string, (bool|positive-int|array{
29
     *   0: positive-int,
30
     *   1: ('var'|'var='|'expr'|'expr='),
31
     *   2?: array<string, bool>
32
     * })>
33
     */
34
    public static $fieldOptions = [
35
        // Tells the `OptionsArray` to not sort the options.
36
        // See the note below.
37
        '_UNSORTED' => true,
38
39
        'NOT NULL' => 1,
40
        'NULL' => 1,
41
        'DEFAULT' => [
42
            2,
43
            'expr',
44
            ['breakOnAlias' => true],
45
        ],
46
        /* Following are not according to grammar, but MySQL happily accepts
47
         * these at any location */
48
        'CHARSET' => [
49
            2,
50
            'var',
51
        ],
52
        'COLLATE' => [
53
            3,
54
            'var',
55
        ],
56
        'AUTO_INCREMENT' => 3,
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 104
    public function __construct(
159
        $name = null,
160
        $options = null,
161
        $type = null,
162
        $isConstraint = false,
163
        $references = null
164
    ) {
165 104
        $this->name = $name;
166 104
        $this->options = $options;
167 104
        if ($type instanceof DataType) {
168 2
            $this->type = $type;
169 104
        } 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 104
    public static function parse(Parser $parser, TokensList $list, array $options = [])
184
    {
185 104
        $ret = [];
186
187 104
        $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 104
        $state = 0;
212
213 104
        for (; $list->idx < $list->count; ++$list->idx) {
214
            /**
215
             * Token parsed at this moment.
216
             */
217 104
            $token = $list->tokens[$list->idx];
218
219
            // End of statement.
220 104
            if ($token->type === Token::TYPE_DELIMITER) {
221 4
                break;
222
            }
223
224
            // Skipping whitespaces and comments.
225 102
            if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
226 96
                continue;
227
            }
228
229 102
            if ($state === 0) {
230 102
                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 100
                $state = 1;
237 100
            } elseif ($state === 1) {
238 100
                if ($token->type === Token::TYPE_KEYWORD && $token->keyword === 'CONSTRAINT') {
239 18
                    $expr->isConstraint = true;
240 100
                } elseif (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_KEY)) {
241 36
                    $expr->key = Key::parse($parser, $list);
242 36
                    $state = 4;
243 100
                } elseif ($token->type === Token::TYPE_SYMBOL || $token->type === Token::TYPE_NONE) {
244 94
                    $expr->name = $token->value;
245 94
                    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 94
                        $state = 2;
247
                    }
248 6
                } elseif ($token->type === Token::TYPE_KEYWORD) {
249 4
                    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 2
                    $expr->name = $token->value;
264 2
                    $state = 2;
265
                } else {
266 2
                    $parser->error('A symbol name was expected!', $token);
267
268 98
                    return $ret;
269
                }
270 96
            } elseif ($state === 2) {
271 96
                $expr->type = DataType::parse($parser, $list);
272 96
                $state = 3;
273 96
            } elseif ($state === 3) {
274 96
                $expr->options = OptionsArray::parse($parser, $list, static::$fieldOptions);
275 96
                $state = 4;
276 96
            } elseif ($state === 4) {
277 96
                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 96
                    --$list->idx;
282
                }
283
284 96
                $state = 5;
285 96
            } elseif ($state === 5) {
286 96
                if (! empty($expr->type) || ! empty($expr->key)) {
287 96
                    $ret[] = $expr;
288
                }
289
290 96
                $expr = new static();
291 96
                if ($token->value === ',') {
292 64
                    $state = 1;
293 94
                } elseif ($token->value === ')') {
294 92
                    $state = 6;
295 92
                    ++$list->idx;
296 92
                    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 100
        if (! empty($expr->type) || ! empty($expr->key)) {
307 2
            $ret[] = $expr;
308
        }
309
310 100
        if (($state !== 0) && ($state !== 6)) {
311 2
            $parser->error('A closing bracket was expected.', $list->tokens[$list->idx - 1]);
312
        }
313
314 100
        --$list->idx;
315
316 100
        return $ret;
317
    }
318
319
    /**
320
     * @param CreateDefinition|CreateDefinition[] $component the component to be built
321
     * @param array<string, mixed>                $options   parameters for building
322
     */
323 34
    public static function build($component, array $options = []): string
324
    {
325 34
        if (is_array($component)) {
326 24
            return "(\n  " . implode(",\n  ", $component) . "\n)";
327
        }
328
329 34
        $tmp = '';
330
331 34
        if ($component->isConstraint) {
332 4
            $tmp .= 'CONSTRAINT ';
333
        }
334
335 34
        if (isset($component->name) && ($component->name !== '')) {
336 32
            $tmp .= Context::escape($component->name) . ' ';
337
        }
338
339 34
        if (! empty($component->type)) {
340 28
            $tmp .= DataType::build(
341 28
                $component->type,
342 28
                ['lowercase' => true]
343 28
            ) . ' ';
344
        }
345
346 34
        if (! empty($component->key)) {
347 12
            $tmp .= $component->key . ' ';
348
        }
349
350 34
        if (! empty($component->references)) {
351 4
            $tmp .= 'REFERENCES ' . $component->references . ' ';
352
        }
353
354 34
        $tmp .= $component->options;
355
356 34
        return trim($tmp);
357
    }
358
359 26
    public function __toString(): string
360
    {
361 26
        return static::build($this);
362
    }
363
}
364