Formatter.php 17.6 KB
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
<?php

/**
 * Utilities that are used for formatting queries.
 *
 * @package    SqlParser
 * @subpackage Utils
 */
namespace SqlParser\Utils;

use SqlParser\Lexer;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;

/**
 * Utilities that are used for formatting queries.
 *
 * @category   Misc
 * @package    SqlParser
 * @subpackage Utils
 * @author     Dan Ungureanu <[email protected]>
 * @license    http://opensource.org/licenses/GPL-2.0 GNU Public License
 */
class Formatter
{

    /**
     * The formatting options.
     *
     * @var array
     */
    public $options;

    /**
     * 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,
        '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())
    {
        // The specified formatting options are merged with the default values.
        $this->options = array_merge(
            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' => $this->options['type'] == 'html' ? '<br/>' : "\n",

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

                /**
                 * 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)
                 *
                 * @var array[]
                 */
                'formats' => array(
                    array(
                        'type'      => Token::TYPE_KEYWORD,
                        'flags'     => Token::FLAG_KEYWORD_RESERVED,
                        'html'      => 'class="sql-reserved"',
                        'cli'      => "\e[35m",
                        'function'  => 'strtoupper',
                    ),
                    array(
                        'type'      => Token::TYPE_KEYWORD,
                        'flags'     => 0,
                        'html'      => 'class="sql-keyword"',
                        'cli'      => "\e[95m",
                        'function'  => 'strtoupper',
                    ),
                    array(
                        'type'      => Token::TYPE_COMMENT,
                        'flags'     => 0,
                        'html'      => 'class="sql-comment"',
                        'cli'      => "\e[37m",
                        'function'  => '',
                    ),
                    array(
                        'type'      => Token::TYPE_BOOL,
                        'flags'     => 0,
                        'html'      => 'class="sql-atom"',
                        'cli'      => "\e[36m",
                        'function'  => 'strtoupper',
                    ),
                    array(
                        'type'      => Token::TYPE_NUMBER,
                        'flags'     => 0,
                        'html'      => 'class="sql-number"',
                        'cli'      => "\e[92m",
                        'function'  => 'strtolower',
                    ),
                    array(
                        'type'      => Token::TYPE_STRING,
                        'flags'     => 0,
                        'html'      => 'class="sql-string"',
                        'cli'      => "\e[91m",
                        'function'  => '',
                    ),
                    array(
                        'type'      => Token::TYPE_SYMBOL,
                        'flags'     => 0,
                        'html'      => 'class="sql-variable"',
                        'cli'      => "\e[36m",
                        'function'  => '',
                    ),
                )
            ),
            $options
        );

        // `parts_newline` requires `clause_newline`
        $this->options['parts_newline'] &= $this->options['clause_newline'];
    }

    /**
     * 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
         */
        $ret = '';

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

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

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

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

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

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

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

        /**
         * Comments are being formatted separately to maintain the whitespaces
         * before and after them.
         *
         * @var string $comment
         */
        $comment = '';

        // 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
             */
            $curr = $list->tokens[$list->idx];

            if ($curr->type === Token::TYPE_WHITESPACE) {
                // Whitespaces are skipped because the formatter adds its own.
                continue;
            } elseif ($curr->type === Token::TYPE_COMMENT) {
                // Whether the comments should be parsed.
                if (!empty($this->options['remove_comments'])) {
                    continue;
                }

                if ($list->tokens[$list->idx - 1]->type === Token::TYPE_WHITESPACE) {
                    // The whitespaces before and after are preserved for
                    // formatting reasons.
                    $comment .= $list->tokens[$list->idx - 1]->token;
                }
                $comment .= $this->toString($curr);
                if (($list->tokens[$list->idx + 1]->type === Token::TYPE_WHITESPACE)
                    && ($list->tokens[$list->idx + 2]->type !== Token::TYPE_COMMENT)
                ) {
                    // Adding the next whitespace only there is no comment that
                    // follows it immediately which may cause adding a
                    // whitespace twice.
                    $comment .= $list->tokens[$list->idx + 1]->token;
                }

                // Everything was handled here, no need to continue.
                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 ($tmp = static::isClause($curr)) {
                    if (($tmp == 2) || ($this->options['clause_newline'])) {
                        $lineEnded = true;
                        if ($this->options['parts_newline']) {
                            --$indent;
                        }
                    }
                }

                // Indenting BEGIN ... END blocks.
                if (($prev->type === Token::TYPE_KEYWORD) && ($prev->value === 'BEGIN')) {
                    $lineEnded = true;
                    array_push($blocksIndentation, $indent);
                    ++$indent;
                } elseif (($curr->type === Token::TYPE_KEYWORD) && ($curr->value === '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 (((empty(self::$INLINE_CLAUSES[$lastClause]))
                        && ($this->options['parts_newline']))
                        || (end($blocksLineEndings) === true)
                    ) {
                        $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 === '(')) {
                    array_push($blocksIndentation, $indent);
                    if (static::getGroupLength($list) > 30) {
                        ++$indent;
                        $lineEnded = true;
                    }
                    array_push($blocksLineEndings, $lineEnded);
                } elseif (($curr->type === Token::TYPE_OPERATOR) && ($curr->value === ')')) {
                    $indent = array_pop($blocksIndentation);
                    $lineEnded |= array_pop($blocksLineEndings);
                }

                // Delimiter must be placed on the same line with the last
                // clause.
                if ($curr->type === Token::TYPE_DELIMITER) {
                    $lineEnded = false;
                }

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

                // Finishing the line.
                if ($lineEnded) {
                    if ($indent < 0) {
                        // TODO: Make sure this never occurs and delete it.
                        $indent = 0;
                    }

                    if ($curr->type !== Token::TYPE_COMMENT) {
                        $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 (!((($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))
                        // A space after delimiters that are longer than 2 characters.
                        || ($prev->value === 'DELIMITER')
                    ) {
                        $ret .= ' ';
                    }
                }
            }

            if (!empty($comment)) {
                $ret .= $comment;
                $comment = '';
            }

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

        return $ret;
    }

    /**
     * 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;

        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'] . '>' . $text . '</span>';
                } elseif ($this->options['type'] === 'cli') {
                    return $format['cli'] . $text;
                }

                break;
            }
        }

        if ($this->options['type'] === 'cli') {
            return "\e[39m" . $text;
        }
        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 Formatter($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
         */
        $count = 1;

        /**
         * The length of this group.
         *
         * @var int $length
         */
        $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_NONE) && (strtoupper($token->token) === 'DELIMITER'))
            || (($token->type === Token::TYPE_KEYWORD) && (isset(Parser::$STATEMENT_PARSERS[$token->value])))
        ) {
            return 2;
        } elseif (($token->type === Token::TYPE_KEYWORD) && (isset(Parser::$KEYWORD_PARSERS[$token->value]))) {
            return 1;
        }
        return false;
    }
}