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

IntoKeyword::__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\Parser;
9
use PhpMyAdmin\SqlParser\Token;
10
use PhpMyAdmin\SqlParser\TokensList;
11
12
use function implode;
13
use function trim;
14
15
/**
16
 * `INTO` keyword parser.
17
 */
18
final class IntoKeyword implements Component
19
{
20
    /**
21
     * FIELDS/COLUMNS Options for `SELECT...INTO` statements.
22
     *
23
     * @var array<string, int|array<int, int|string>>
24
     * @psalm-var array<string, (positive-int|array{positive-int, ('var'|'var='|'expr'|'expr=')})>
25
     */
26
    public static $statementFieldsOptions = [
27
        'TERMINATED BY' => [
28
            1,
29
            'expr',
30
        ],
31
        'OPTIONALLY' => 2,
32
        'ENCLOSED BY' => [
33
            3,
34
            'expr',
35
        ],
36
        'ESCAPED BY' => [
37
            4,
38
            'expr',
39
        ],
40
    ];
41
42
    /**
43
     * LINES Options for `SELECT...INTO` statements.
44
     *
45
     * @var array<string, int|array<int, int|string>>
46
     * @psalm-var array<string, (positive-int|array{positive-int, ('var'|'var='|'expr'|'expr=')})>
47
     */
48
    public static $statementLinesOptions = [
49
        'STARTING BY' => [
50
            1,
51
            'expr',
52
        ],
53
        'TERMINATED BY' => [
54
            2,
55
            'expr',
56
        ],
57
    ];
58
59
    /**
60
     * Type of target (OUTFILE or SYMBOL).
61
     *
62
     * @var string|null
63
     */
64
    public $type;
65
66
    /**
67
     * The destination, which can be a table or a file.
68
     *
69
     * @var string|Expression|null
70
     */
71
    public $dest;
72
73
    /**
74
     * The name of the columns.
75
     *
76
     * @var string[]|null
77
     */
78
    public $columns;
79
80
    /**
81
     * The values to be selected into (SELECT .. INTO @var1).
82
     *
83
     * @var Expression[]|null
84
     */
85
    public $values;
86
87
    /**
88
     * Options for FIELDS/COLUMNS keyword.
89
     *
90
     * @see IntoKeyword::$statementFieldsOptions
91
     *
92
     * @var OptionsArray|null
93
     */
94
    public $fieldsOptions;
95
96
    /**
97
     * Whether to use `FIELDS` or `COLUMNS` while building.
98
     *
99
     * @var bool|null
100
     */
101
    public $fieldsKeyword;
102
103
    /**
104
     * Options for OPTIONS keyword.
105
     *
106
     * @see IntoKeyword::$statementLinesOptions
107
     *
108
     * @var OptionsArray|null
109
     */
110
    public $linesOptions;
111
112
    /**
113
     * @param string|null            $type          type of destination (may be OUTFILE)
114
     * @param string|Expression|null $dest          actual destination
115
     * @param string[]|null          $columns       column list of destination
116
     * @param Expression[]|null      $values        selected fields
117
     * @param OptionsArray|null      $fieldsOptions options for FIELDS/COLUMNS keyword
118
     * @param bool|null              $fieldsKeyword options for OPTIONS keyword
119
     */
120 88
    public function __construct(
121
        $type = null,
122
        $dest = null,
123
        $columns = null,
124
        $values = null,
125
        $fieldsOptions = null,
126
        $fieldsKeyword = null
127
    ) {
128 88
        $this->type = $type;
129 88
        $this->dest = $dest;
130 88
        $this->columns = $columns;
131 88
        $this->values = $values;
132 88
        $this->fieldsOptions = $fieldsOptions;
133 88
        $this->fieldsKeyword = $fieldsKeyword;
134
    }
135
136
    /**
137
     * @param Parser               $parser  the parser that serves as context
138
     * @param TokensList           $list    the list of tokens that are being parsed
139
     * @param array<string, mixed> $options parameters for parsing
140
     *
141
     * @return IntoKeyword
142
     */
143 88
    public static function parse(Parser $parser, TokensList $list, array $options = [])
144
    {
145 88
        $ret = new static();
146
147
        /**
148
         * The state of the parser.
149
         *
150
         * Below are the states of the parser.
151
         *
152
         *      0 -----------------------[ name ]----------------------> 1
153
         *      0 ---------------------[ OUTFILE ]---------------------> 2
154
         *
155
         *      1 ------------------------[ ( ]------------------------> (END)
156
         *
157
         *      2 ---------------------[ filename ]--------------------> 1
158
         *
159
         * @var int
160
         */
161 88
        $state = 0;
162
163 88
        for (; $list->idx < $list->count; ++$list->idx) {
164
            /**
165
             * Token parsed at this moment.
166
             */
167 88
            $token = $list->tokens[$list->idx];
168
169
            // End of statement.
170 88
            if ($token->type === Token::TYPE_DELIMITER) {
171 14
                break;
172
            }
173
174
            // Skipping whitespaces and comments.
175 88
            if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
176 82
                continue;
177
            }
178
179 88
            if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_RESERVED)) {
180 44
                if (($state === 0) && ($token->keyword === 'OUTFILE')) {
181 20
                    $ret->type = 'OUTFILE';
182 20
                    $state = 2;
183 20
                    continue;
184
                }
185
186
                // No other keyword is expected except for $state = 4, which expects `LINES`
187 34
                if ($state !== 4) {
188 32
                    break;
189
                }
190
            }
191
192 86
            if ($state === 0) {
193
                if (
194 68
                    (isset($options['fromInsert'])
195 38
                    && $options['fromInsert'])
196 68
                    || (isset($options['fromReplace'])
197 68
                    && $options['fromReplace'])
198
                ) {
199 64
                    $ret->dest = Expression::parse(
200 64
                        $parser,
201 64
                        $list,
202 64
                        [
203 64
                            'parseField' => 'table',
204 64
                            'breakOnAlias' => true,
205 64
                        ]
206 64
                    );
207
                } else {
208 4
                    $ret->values = ExpressionArray::parse($parser, $list);
209
                }
210
211 68
                $state = 1;
212 62
            } elseif ($state === 1) {
213 44
                if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
214 40
                    $ret->columns = ArrayObj::parse($parser, $list)->values;
215 40
                    ++$list->idx;
216
                }
217
218 44
                break;
219 18
            } elseif ($state === 2) {
220 18
                $ret->dest = $token->value;
221
222 18
                $state = 3;
223 8
            } elseif ($state === 3) {
224 8
                $ret->parseFileOptions($parser, $list, $token->value);
225 8
                $state = 4;
226 8
            } elseif ($state === 4) {
227 8
                if ($token->type === Token::TYPE_KEYWORD && $token->keyword !== 'LINES') {
228 2
                    break;
229
                }
230
231 6
                $ret->parseFileOptions($parser, $list, $token->value);
232 6
                $state = 5;
233
            }
234
        }
235
236 88
        --$list->idx;
237
238 88
        return $ret;
239
    }
240
241
    /**
242
     * @param Parser     $parser  The parser
243
     * @param TokensList $list    A token list
244
     * @param string     $keyword They keyword
245
     *
246
     * @return void
247
     */
248 8
    public function parseFileOptions(Parser $parser, TokensList $list, $keyword = 'FIELDS')
249
    {
250 8
        ++$list->idx;
251
252 8
        if ($keyword === 'FIELDS' || $keyword === 'COLUMNS') {
253
            // parse field options
254 8
            $this->fieldsOptions = OptionsArray::parse($parser, $list, static::$statementFieldsOptions);
255
256 8
            $this->fieldsKeyword = ($keyword === 'FIELDS');
257
        } else {
258
            // parse line options
259 6
            $this->linesOptions = OptionsArray::parse($parser, $list, static::$statementLinesOptions);
260
        }
261
    }
262
263
    /**
264
     * @param IntoKeyword          $component the component to be built
265
     * @param array<string, mixed> $options   parameters for building
266
     */
267 18
    public static function build($component, array $options = []): string
268
    {
269 18
        if ($component->dest instanceof Expression) {
270 10
            $columns = ! empty($component->columns) ? '(`' . implode('`, `', $component->columns) . '`)' : '';
271
272 10
            return $component->dest . $columns;
273
        }
274
275 8
        if (isset($component->values)) {
276 4
            return ExpressionArray::build($component->values);
277
        }
278
279 4
        $ret = 'OUTFILE "' . $component->dest . '"';
280
281 4
        $fieldsOptionsString = OptionsArray::build($component->fieldsOptions);
282 4
        if (trim($fieldsOptionsString) !== '') {
283 2
            $ret .= $component->fieldsKeyword ? ' FIELDS' : ' COLUMNS';
284 2
            $ret .= ' ' . $fieldsOptionsString;
285
        }
286
287 4
        $linesOptionsString = OptionsArray::build($component->linesOptions, ['expr' => true]);
288 4
        if (trim($linesOptionsString) !== '') {
289 2
            $ret .= ' LINES ' . $linesOptionsString;
290
        }
291
292 4
        return $ret;
293
    }
294
295 10
    public function __toString(): string
296
    {
297 10
        return static::build($this);
298
    }
299
}
300