Formatter.php 21.7 KB
Newer Older
Hamza Arfaoui's avatar
Hamza Arfaoui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
<?php

/**
 * Utilities that are used for formatting queries.
 */

namespace PhpMyAdmin\SqlParser\Utils;

use PhpMyAdmin\SqlParser\Components\JoinKeyword;
use PhpMyAdmin\SqlParser\Lexer;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;

/**
 * Utilities that are used for formatting queries.
 *
 * @category   Misc
 *
 * @license    https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
 */
class Formatter
{
    /**
     * The formatting options.
     *
     * @var array
     */
    public $options;

    /**
     * Clauses that are usually short.
     *
     * These clauses share the line with the next clause.
     *
     * E.g. if INSERT was not here, the formatter would produce:
     *
     *      INSERT
     *      INTO foo
     *      VALUES(0, 0, 0),(1, 1, 1);
     *
     * Instead of:
     *
     *      INSERT INTO foo
     *      VALUES(0, 0, 0),(1, 1, 1)
     *
     * @var array
     */
    public static $SHORT_CLAUSES = array(
        'CREATE' => true,
        'INSERT' => true
    );

    /**
     * Clauses that must be inlined.
     *
     * These clauses usually are short and it's nicer to have them inline.
     *
     * @var array
     */
    public static $INLINE_CLAUSES = array(
        'CREATE' => true,
        'INTO' => true,
        'LIMIT' => true,
        'PARTITION BY' => true,
        'PARTITION' => true,
        'PROCEDURE' => true,
        'SUBPARTITION BY' => true,
        'VALUES' => true
    );

    /**
     * Constructor.
     *
     * @param array $options the formatting options
     */
    public function __construct(array $options = array())
    {
        $this->options = $this->getMergedOptions($options);
    }

    /**
     * The specified formatting options are merged with the default values.
     *
     * @param array $options
     *
     * @return array
     */
    private function getMergedOptions(array $options)
    {
        $options = array_merge(
            $this->getDefaultOptions(),
            $options
        );

        if (isset($options['formats'])) {
            $options['formats'] = self::mergeFormats($this->getDefaultFormats(), $options['formats']);
        } else {
            $options['formats'] = $this->getDefaultFormats();
        }

        if (is_null($options['line_ending'])) {
            $options['line_ending'] = $options['type'] === 'html' ? '<br/>' : "\n";
        }

        if (is_null($options['indentation'])) {
            $options['indentation'] = $options['type'] === 'html' ? '&nbsp;&nbsp;&nbsp;&nbsp;' : '    ';
        }

        // `parts_newline` requires `clause_newline`
        $options['parts_newline'] &= $options['clause_newline'];

        return $options;
    }

    /**
     * The default formatting options.
     *
     * @return array
     */
    protected function getDefaultOptions()
    {
        return array(
            /*
             * The format of the result.
             *
             * @var string The type ('text', 'cli' or 'html')
             */
            'type' => php_sapi_name() === 'cli' ? 'cli' : 'text',

            /*
             * The line ending used.
             * By default, for text this is "\n" and for HTML this is "<br/>".
             *
             * @var string
             */
            'line_ending' => null,

            /*
             * The string used for indentation.
             *
             * @var string
             */
            'indentation' => null,

            /*
             * Whether comments should be removed or not.
             *
             * @var bool
             */
            'remove_comments' => false,

            /*
             * Whether each clause should be on a new line.
             *
             * @var bool
             */
            'clause_newline' => true,

            /*
             * Whether each part should be on a new line.
             * Parts are delimited by brackets and commas.
             *
             * @var bool
             */
            'parts_newline' => true,

            /*
             * Whether each part of each clause should be indented.
             *
             * @var bool
             */
            'indent_parts' => true
        );
    }

    /**
     * The styles used for HTML formatting.
     * array($type, $flags, $span, $callback).
     *
     * @return array
     */
    protected function getDefaultFormats()
    {
        return array(
            array(
                'type' => Token::TYPE_KEYWORD,
                'flags' => Token::FLAG_KEYWORD_RESERVED,
                'html' => 'class="sql-reserved"',
                'cli' => "\x1b[35m",
                'function' => 'strtoupper',
            ),
            array(
                'type' => Token::TYPE_KEYWORD,
                'flags' => 0,
                'html' => 'class="sql-keyword"',
                'cli' => "\x1b[95m",
                'function' => 'strtoupper',
            ),
            array(
                'type' => Token::TYPE_COMMENT,
                'flags' => 0,
                'html' => 'class="sql-comment"',
                'cli' => "\x1b[37m",
                'function' => '',
            ),
            array(
                'type' => Token::TYPE_BOOL,
                'flags' => 0,
                'html' => 'class="sql-atom"',
                'cli' => "\x1b[36m",
                'function' => 'strtoupper',
            ),
            array(
                'type' => Token::TYPE_NUMBER,
                'flags' => 0,
                'html' => 'class="sql-number"',
                'cli' => "\x1b[92m",
                'function' => 'strtolower',
            ),
            array(
                'type' => Token::TYPE_STRING,
                'flags' => 0,
                'html' => 'class="sql-string"',
                'cli' => "\x1b[91m",
                'function' => '',
            ),
            array(
                'type' => Token::TYPE_SYMBOL,
                'flags' => Token::FLAG_SYMBOL_PARAMETER,
                'html' => 'class="sql-parameter"',
                'cli' => "\x1b[31m",
                'function' => '',
            ),
            array(
                'type' => Token::TYPE_SYMBOL,
                'flags' => 0,
                'html' => 'class="sql-variable"',
                'cli' => "\x1b[36m",
                'function' => '',
            )
        );
    }

    private static function mergeFormats(array $formats, array $newFormats)
    {
        $added = array();
        $integers = array(
            'flags',
            'type'
        );
        $strings = array(
            'html',
            'cli',
            'function'
        );

        /* Sanitize the array so that we do not have to care later */
        foreach ($newFormats as $j => $new) {
            foreach ($integers as $name) {
                if (! isset($new[$name])) {
                    $newFormats[$j][$name] = 0;
                }
            }
            foreach ($strings as $name) {
                if (! isset($new[$name])) {
                    $newFormats[$j][$name] = '';
                }
            }
        }

        /* Process changes to existing formats */
        foreach ($formats as $i => $original) {
            foreach ($newFormats as $j => $new) {
                if ($new['type'] === $original['type']
                    && $original['flags'] === $new['flags']
                ) {
                    $formats[$i] = $new;
                    $added[] = $j;
                }
            }
        }

        /* Add not already handled formats */
        foreach ($newFormats as $j => $new) {
            if (! in_array($j, $added)) {
                $formats[] = $new;
            }
        }

        return $formats;
    }

    /**
     * Formats the given list of tokens.
     *
     * @param TokensList $list the list of tokens
     *
     * @return string
     */
    public function formatList($list)
    {
        /**
         * The query to be returned.
         *
         * @var string
         */
        $ret = '';

        /**
         * The indentation level.
         *
         * @var int
         */
        $indent = 0;

        /**
         * Whether the line ended.
         *
         * @var bool
         */
        $lineEnded = false;

        /**
         * Whether current group is short (no linebreaks).
         *
         * @var bool
         */
        $shortGroup = false;

        /**
         * The name of the last clause.
         *
         * @var string
         */
        $lastClause = '';

        /**
         * A stack that keeps track of the indentation level every time a new
         * block is found.
         *
         * @var array
         */
        $blocksIndentation = array();

        /**
         * A stack that keeps track of the line endings every time a new block
         * is found.
         *
         * @var array
         */
        $blocksLineEndings = array();

        /**
         * Whether clause's options were formatted.
         *
         * @var bool
         */
        $formattedOptions = false;

        /**
         * Previously parsed token.
         *
         * @var Token|null
         */
        $prev = null;

        // In order to be able to format the queries correctly, the next token
        // must be taken into consideration. The loop below uses two pointers,
        // `$prev` and `$curr` which store two consecutive tokens.
        // Actually, at every iteration the previous token is being used.
        for ($list->idx = 0; $list->idx < $list->count; ++$list->idx) {
            /**
             * Token parsed at this moment.
             *
             * @var Token
             */
            $curr = $list->tokens[$list->idx];
            if ($list->idx + 1 < $list->count) {
                $next = $list->tokens[$list->idx + 1];
            } else {
                $next = null;
            }

            if ($curr->type === Token::TYPE_WHITESPACE) {
                // Keep linebreaks before and after comments
                if (strpos($curr->token, "\n") !== false && (
                        ($prev !== null && $prev->type === Token::TYPE_COMMENT) ||
                        ($next !== null && $next->type === Token::TYPE_COMMENT)
                    )
                ) {
                    $lineEnded = true;
                }
                // Whitespaces are skipped because the formatter adds its own.
                continue;
            }

            if ($curr->type === Token::TYPE_COMMENT && $this->options['remove_comments']) {
                // Skip Comments if option `remove_comments` is enabled
                continue;
            }

            // Checking if pointers were initialized.
            if ($prev !== null) {
                // Checking if a new clause started.
                if (static::isClause($prev) !== false) {
                    $lastClause = $prev->value;
                    $formattedOptions = false;
                }

                // The options of a clause should stay on the same line and everything that follows.
                if ($this->options['parts_newline']
                    && ! $formattedOptions
                    && empty(self::$INLINE_CLAUSES[$lastClause])
                    && (
                        $curr->type !== Token::TYPE_KEYWORD
                        || (
                            $curr->type === Token::TYPE_KEYWORD
                            && $curr->flags & Token::FLAG_KEYWORD_FUNCTION
                        )
                    )
                ) {
                    $formattedOptions = true;
                    $lineEnded = true;
                    ++$indent;
                }

                // Checking if this clause ended.
                if ($isClause = static::isClause($curr)) {
                    if (($isClause === 2 || $this->options['clause_newline']) && empty(self::$SHORT_CLAUSES[$lastClause])) {
                        $lineEnded = true;
                        if ($this->options['parts_newline'] && $indent > 0) {
                            --$indent;
                        }
                    }
                }

                // Inline JOINs
                if (($prev->type === Token::TYPE_KEYWORD && isset(JoinKeyword::$JOINS[$prev->value]))
                    || (in_array($curr->value, array('ON', 'USING'), true) && isset(JoinKeyword::$JOINS[$list->tokens[$list->idx - 2]->value]))
                    || isset($list->tokens[$list->idx - 4], JoinKeyword::$JOINS[$list->tokens[$list->idx - 4]->value])
                    || isset($list->tokens[$list->idx - 6], JoinKeyword::$JOINS[$list->tokens[$list->idx - 6]->value])
                ) {
                    $lineEnded = false;
                }

                // Indenting BEGIN ... END blocks.
                if ($prev->type === Token::TYPE_KEYWORD && $prev->keyword === 'BEGIN') {
                    $lineEnded = true;
                    $blocksIndentation[] = $indent;
                    ++$indent;
                } elseif ($curr->type === Token::TYPE_KEYWORD && $curr->keyword === 'END') {
                    $lineEnded = true;
                    $indent = array_pop($blocksIndentation);
                }

                // Formatting fragments delimited by comma.
                if ($prev->type === Token::TYPE_OPERATOR && $prev->value === ',') {
                    // Fragments delimited by a comma are broken into multiple
                    // pieces only if the clause is not inlined or this fragment
                    // is between brackets that are on new line.
                    if (end($blocksLineEndings) === true
                        || (
                            empty(self::$INLINE_CLAUSES[$lastClause])
                            && ! $shortGroup
                            && $this->options['parts_newline']
                        )
                    ) {
                        $lineEnded = true;
                    }
                }

                // Handling brackets.
                // Brackets are indented only if the length of the fragment between
                // them is longer than 30 characters.
                if ($prev->type === Token::TYPE_OPERATOR && $prev->value === '(') {
                    $blocksIndentation[] = $indent;
                    $shortGroup = true;
                    if (static::getGroupLength($list) > 30) {
                        ++$indent;
                        $lineEnded = true;
                        $shortGroup = false;
                    }
                    $blocksLineEndings[] = $lineEnded;
                } elseif ($curr->type === Token::TYPE_OPERATOR && $curr->value === ')') {
                    $indent = array_pop($blocksIndentation);
                    $lineEnded |= array_pop($blocksLineEndings);
                    $shortGroup = false;
                }

                // Adding the token.
                $ret .= $this->toString($prev);

                // Finishing the line.
                if ($lineEnded) {
                    $ret .= $this->options['line_ending']
                        . str_repeat($this->options['indentation'], $indent);

                    $lineEnded = false;
                } else {
                    // If the line ended there is no point in adding whitespaces.
                    // Also, some tokens do not have spaces before or after them.
                    if (// A space after delimiters that are longer than 2 characters.
                        $prev->keyword === 'DELIMITER'
                        || ! (
                            ($prev->type === Token::TYPE_OPERATOR && ($prev->value === '.' || $prev->value === '('))
                            // No space after . (
                            || ($curr->type === Token::TYPE_OPERATOR && ($curr->value === '.' || $curr->value === ',' || $curr->value === '(' || $curr->value === ')'))
                            // No space before . , ( )
                            || $curr->type === Token::TYPE_DELIMITER && mb_strlen($curr->value, 'UTF-8') < 2
                        )
                    ) {
                        $ret .= ' ';
                    }
                }
            }

            // Iteration finished, consider current token as previous.
            $prev = $curr;
        }

        if ($this->options['type'] === 'cli') {
            return $ret . "\x1b[0m";
        }

        return $ret;
    }

    public function escapeConsole($string)
    {
        return str_replace(
            array(
                "\x00",
                "\x01",
                "\x02",
                "\x03",
                "\x04",
                "\x05",
                "\x06",
                "\x07",
                "\x08",
                "\x09",
                "\x0A",
                "\x0B",
                "\x0C",
                "\x0D",
                "\x0E",
                "\x0F",
                "\x10",
                "\x11",
                "\x12",
                "\x13",
                "\x14",
                "\x15",
                "\x16",
                "\x17",
                "\x18",
                "\x19",
                "\x1A",
                "\x1B",
                "\x1C",
                "\x1D",
                "\x1E",
                "\x1F",
            ),
            array(
                '\x00',
                '\x01',
                '\x02',
                '\x03',
                '\x04',
                '\x05',
                '\x06',
                '\x07',
                '\x08',
                '\x09',
                '\x0A',
                '\x0B',
                '\x0C',
                '\x0D',
                '\x0E',
                '\x0F',
                '\x10',
                '\x11',
                '\x12',
                '\x13',
                '\x14',
                '\x15',
                '\x16',
                '\x17',
                '\x18',
                '\x19',
                '\x1A',
                '\x1B',
                '\x1C',
                '\x1D',
                '\x1E',
                '\x1F',
            ),
            $string
        );
    }

    /**
     * Tries to print the query and returns the result.
     *
     * @param Token $token the token to be printed
     *
     * @return string
     */
    public function toString($token)
    {
        $text = $token->token;
        static $prev;

        foreach ($this->options['formats'] as $format) {
            if ($token->type === $format['type']
                && ($token->flags & $format['flags']) === $format['flags']
            ) {
                // Running transformation function.
                if (! empty($format['function'])) {
                    $func = $format['function'];
                    $text = $func($text);
                }

                // Formatting HTML.
                if ($this->options['type'] === 'html') {
                    return '<span ' . $format['html'] . '>' . htmlspecialchars($text, ENT_NOQUOTES) . '</span>';
                } elseif ($this->options['type'] === 'cli') {
                    if ($prev !== $format['cli']) {
                        $prev = $format['cli'];

                        return $format['cli'] . $this->escapeConsole($text);
                    }

                    return $this->escapeConsole($text);
                }

                break;
            }
        }

        if ($this->options['type'] === 'cli') {
            if ($prev !== "\x1b[39m") {
                $prev = "\x1b[39m";

                return "\x1b[39m" . $this->escapeConsole($text);
            }

            return $this->escapeConsole($text);
        } elseif ($this->options['type'] === 'html') {
            return htmlspecialchars($text, ENT_NOQUOTES);
        }

        return $text;
    }

    /**
     * Formats a query.
     *
     * @param string $query   The query to be formatted
     * @param array  $options the formatting options
     *
     * @return string the formatted string
     */
    public static function format($query, array $options = array())
    {
        $lexer = new Lexer($query);
        $formatter = new self($options);

        return $formatter->formatList($lexer->list);
    }

    /**
     * Computes the length of a group.
     *
     * A group is delimited by a pair of brackets.
     *
     * @param TokensList $list the list of tokens
     *
     * @return int
     */
    public static function getGroupLength($list)
    {
        /**
         * The number of opening brackets found.
         * This counter starts at one because by the time this function called,
         * the list already advanced one position and the opening bracket was
         * already parsed.
         *
         * @var int
         */
        $count = 1;

        /**
         * The length of this group.
         *
         * @var int
         */
        $length = 0;

        for ($idx = $list->idx; $idx < $list->count; ++$idx) {
            // Counting the brackets.
            if ($list->tokens[$idx]->type === Token::TYPE_OPERATOR) {
                if ($list->tokens[$idx]->value === '(') {
                    ++$count;
                } elseif ($list->tokens[$idx]->value === ')') {
                    --$count;
                    if ($count === 0) {
                        break;
                    }
                }
            }

            // Keeping track of this group's length.
            $length += mb_strlen($list->tokens[$idx]->value, 'UTF-8');
        }

        return $length;
    }

    /**
     * Checks if a token is a statement or a clause inside a statement.
     *
     * @param Token $token the token to be checked
     *
     * @return int|bool
     */
    public static function isClause($token)
    {
        if (($token->type === Token::TYPE_KEYWORD && isset(Parser::$STATEMENT_PARSERS[$token->keyword]))
            || ($token->type === Token::TYPE_NONE && strtoupper($token->token) === 'DELIMITER')
        ) {
            return 2;
        } elseif ($token->type === Token::TYPE_KEYWORD && isset(Parser::$KEYWORD_PARSERS[$token->keyword])
        ) {
            return 1;
        }

        return false;
    }
}