Passed
Push — master ( 6c3f09...c54108 )
by William
03:43
created

Key::__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 definition of a key.
18
 *
19
 * Used for parsing `CREATE TABLE` statement.
20
 */
21
final class Key implements Component
22
{
23
    /**
24
     * All key options.
25
     *
26
     * @var array<string, int|array<int, int|string>>
27
     * @psalm-var array<string, (positive-int|array{positive-int, ('var'|'var='|'expr'|'expr=')})>
28
     */
29
    public static $keyOptions = [
30
        'KEY_BLOCK_SIZE' => [
31
            1,
32
            'var=',
33
        ],
34
        'USING' => [
35
            2,
36
            'var',
37
        ],
38
        'WITH PARSER' => [
39
            3,
40
            'var',
41
        ],
42
        'COMMENT' => [
43
            4,
44
            'var',
45
        ],
46
        // MariaDB options
47
        'CLUSTERING' => [
48
            4,
49
            'var=',
50
        ],
51
        'ENGINE_ATTRIBUTE' => [
52
            5,
53
            'var=',
54
        ],
55
        'SECONDARY_ENGINE_ATTRIBUTE' => [
56
            5,
57
            'var=',
58
        ],
59
        // MariaDB & MySQL options
60
        'VISIBLE' => 6,
61
        'INVISIBLE' => 6,
62
        // MariaDB options
63
        'IGNORED' => 10,
64
        'NOT IGNORED' => 10,
65
    ];
66
67
    /**
68
     * The name of this key.
69
     *
70
     * @var string
71
     */
72
    public $name;
73
74
    /**
75
     * The key columns
76
     *
77
     * @var array<int, array<string, int|string>>
78
     * @phpstan-var array{name?: string, length?: int, order?: string}[]
79
     */
80
    public $columns;
81
82
    /**
83
     * The type of this key.
84
     *
85
     * @var string
86
     */
87
    public $type;
88
89
    /**
90
     * The expression if the Key is not using column names
91
     *
92
     * @var string|null
93
     */
94
    public $expr = null;
95
96
    /**
97
     * The options of this key or null if none where found.
98
     *
99
     * @var OptionsArray|null
100
     */
101
    public $options;
102
103
    /**
104
     * @param string                                $name    the name of the key
105
     * @param array<int, array<string, int|string>> $columns the columns covered by this key
106
     * @param string                                $type    the type of this key
107
     * @param OptionsArray                          $options the options of this key
108
     * @phpstan-param array{name?: string, length?: int, order?: string}[] $columns
109
     */
110 62
    public function __construct(
111
        $name = null,
112
        array $columns = [],
113
        $type = null,
114
        $options = null
115
    ) {
116 62
        $this->name = $name;
117 62
        $this->columns = $columns;
118 62
        $this->type = $type;
119 62
        $this->options = $options;
120
    }
121
122
    /**
123
     * @param Parser               $parser  the parser that serves as context
124
     * @param TokensList           $list    the list of tokens that are being parsed
125
     * @param array<string, mixed> $options parameters for parsing
126
     *
127
     * @return Key
128
     */
129 62
    public static function parse(Parser $parser, TokensList $list, array $options = [])
130
    {
131 62
        $ret = new static();
132
133
        /**
134
         * Last parsed column.
135
         *
136
         * @var array<string,mixed>
137
         */
138 62
        $lastColumn = [];
139
140
        /**
141
         * The state of the parser.
142
         *
143
         * Below are the states of the parser.
144
         *
145
         *      0 ---------------------[ type ]---------------------------> 1
146
         *
147
         *      1 ---------------------[ name ]---------------------------> 1
148
         *      1 ---------------------[ columns ]------------------------> 2
149
         *      1 ---------------------[ expression ]---------------------> 5
150
         *
151
         *      2 ---------------------[ column length ]------------------> 3
152
         *      3 ---------------------[ column length ]------------------> 2
153
         *      2 ---------------------[ options ]------------------------> 4
154
         *      5 ---------------------[ expression ]---------------------> 4
155
         *
156
         * @var int
157
         */
158 62
        $state = 0;
159
160 62
        for (; $list->idx < $list->count; ++$list->idx) {
161
            /**
162
             * Token parsed at this moment.
163
             */
164 62
            $token = $list->tokens[$list->idx];
165
166
            // End of statement.
167 62
            if ($token->type === Token::TYPE_DELIMITER) {
168 4
                break;
169
            }
170
171
            // Skipping whitespaces and comments.
172 60
            if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
173 60
                continue;
174
            }
175
176 60
            if ($state === 0) {
177 60
                $ret->type = $token->value;
178 60
                $state = 1;
179 60
            } elseif ($state === 1) {
180 60
                if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
181 60
                    $positionBeforeSearch = $list->idx;
182 60
                    $list->idx++;// Ignore the current token "(" or the search condition will always be true
183 60
                    $nextToken = $list->getNext();
184 60
                    $list->idx = $positionBeforeSearch;// Restore the position
185
186 60
                    if ($nextToken !== null && $nextToken->value === '(') {
187
                        // Switch to expression mode
188 12
                        $state = 5;
189
                    } else {
190 60
                        $state = 2;
191
                    }
192
                } else {
193 60
                    $ret->name = $token->value;
194
                }
195 60
            } elseif ($state === 2) {
196 50
                if ($token->type === Token::TYPE_OPERATOR) {
197 50
                    if ($token->value === '(') {
198 14
                        $state = 3;
199 50
                    } elseif (($token->value === ',') || ($token->value === ')')) {
200 50
                        $state = $token->value === ',' ? 2 : 4;
201 50
                        if (! empty($lastColumn)) {
202 50
                            $ret->columns[] = $lastColumn;
203 50
                            $lastColumn = [];
204
                        }
205
                    }
206
                } elseif (
207
                    (
208 50
                        $token->type === Token::TYPE_KEYWORD
209
                    )
210
                    &&
211
                    (
212 50
                        ($token->keyword === 'ASC') || ($token->keyword === 'DESC')
213
                    )
214
                ) {
215 8
                    $lastColumn['order'] = $token->keyword;
216
                } else {
217 50
                    $lastColumn['name'] = $token->value;
218
                }
219 58
            } elseif ($state === 3) {
220 14
                if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ')')) {
221 14
                    $state = 2;
222
                } else {
223 14
                    $lastColumn['length'] = $token->value;
224
                }
225 58
            } elseif ($state === 4) {
226 58
                $ret->options = OptionsArray::parse($parser, $list, static::$keyOptions);
227 58
                ++$list->idx;
228 58
                break;
229 12
            } elseif ($state === 5) {
230 12
                if ($token->type === Token::TYPE_OPERATOR) {
231
                    // This got back to here and we reached the end of the expression
232 12
                    if ($token->value === ')') {
233 12
                        $state = 4;// go back to state 4 to fetch options
234 12
                        continue;
235
                    }
236
237
                    // The expression is not finished, adding a separator for the next expression
238 12
                    if ($token->value === ',') {
239 6
                        $ret->expr .= ', ';
240 6
                        continue;
241
                    }
242
243
                    // Start of the expression
244 12
                    if ($token->value === '(') {
245
                        // This is the first expression, set to empty
246 12
                        if ($ret->expr === null) {
247 12
                            $ret->expr = '';
248
                        }
249
250 12
                        $ret->expr .= Expression::parse($parser, $list, ['parenthesesDelimited' => true]);
251 12
                        continue;
252
                    }
253
                    // Another unexpected operator was found
254
                }
255
256
                // Something else than an operator was found
257 2
                $parser->error('Unexpected token.', $token);
258
            }
259
        }
260
261 62
        --$list->idx;
262
263 62
        return $ret;
264
    }
265
266
    /**
267
     * @param Key                  $component the component to be built
268
     * @param array<string, mixed> $options   parameters for building
269
     */
270 36
    public static function build($component, array $options = []): string
271
    {
272 36
        $ret = $component->type . ' ';
273 36
        if (! empty($component->name)) {
274 30
            $ret .= Context::escape($component->name) . ' ';
275
        }
276
277 36
        if ($component->expr !== null) {
278 12
            return $ret . '(' . $component->expr . ') ' . $component->options;
279
        }
280
281 26
        $columns = [];
282 26
        foreach ($component->columns as $column) {
283 24
            $tmp = '';
284 24
            if (isset($column['name'])) {
285 24
                $tmp .= Context::escape($column['name']);
286
            }
287
288 24
            if (isset($column['length'])) {
289 10
                $tmp .= '(' . $column['length'] . ')';
290
            }
291
292 24
            if (isset($column['order'])) {
293 8
                $tmp .= ' ' . $column['order'];
294
            }
295
296 24
            $columns[] = $tmp;
297
        }
298
299 26
        $ret .= '(' . implode(',', $columns) . ') ' . $component->options;
300
301 26
        return trim($ret);
302
    }
303
304 12
    public function __toString(): string
305
    {
306 12
        return static::build($this);
307
    }
308
}
309