diff --git a/README.md b/README.md index 767d6de..7ca5041 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,19 @@ use Doctrine\SqlFormatter\SqlFormatter; echo (new SqlFormatter(new NullHighlighter()))->format($query); ``` +#### Forcing uppercase for SQL keywords + +If you wish to also force SQL keywords to be uppercase, you can do the following: + +```php +format($query, ' ', true); +``` + Output: ![](http://jdorn.github.com/sql-formatter/format.png) diff --git a/src/SqlFormatter.php b/src/SqlFormatter.php index 624c3bb..b0440e8 100644 --- a/src/SqlFormatter.php +++ b/src/SqlFormatter.php @@ -6,7 +6,7 @@ * SQL Formatter is a collection of utilities for debugging SQL queries. * It includes methods for formatting, syntax highlighting, removing comments, etc. * - * @link http://github.com/jdorn/sql-formatter + * @see http://github.com/jdorn/sql-formatter */ namespace Doctrine\SqlFormatter; @@ -16,12 +16,14 @@ use function array_unshift; use function assert; use function current; +use function in_array; use function preg_replace; use function reset; use function rtrim; use function str_repeat; use function str_replace; use function strlen; +use function strtoupper; use function trim; use const PHP_SAPI; @@ -47,7 +49,7 @@ public function __construct(?Highlighter $highlighter = null) * * @return string The SQL string with HTML styles and formatting wrapped in a
tag */ - public function format(string $string, string $indentString = ' '): string + public function format(string $string, string $indentString = ' ', bool $forceUppercase = false): string { // This variable will be populated with formatted html $return = ''; @@ -71,9 +73,23 @@ public function format(string $string, string $indentString = ' '): string // Format token by token while ($token = $cursor->next(Token::TOKEN_TYPE_WHITESPACE)) { + // Uppercase reserved words + $uppercaseTypes = [ + Token::TOKEN_TYPE_RESERVED, + Token::TOKEN_TYPE_RESERVED_NEWLINE, + Token::TOKEN_TYPE_RESERVED_TOPLEVEL, + ]; + + // Uppercase transformation if desired + if ($forceUppercase && in_array($token->type(), $uppercaseTypes)) { + $tokenValue = strtoupper($token->value()); + } else { + $tokenValue = $token->value(); + } + $highlighted = $this->highlighter->highlightToken( $token->type(), - $token->value() + $tokenValue ); // If we are increasing the special indent level now diff --git a/tests/SqlFormatterTest.php b/tests/SqlFormatterTest.php index 68d90cd..f5c8aed 100644 --- a/tests/SqlFormatterTest.php +++ b/tests/SqlFormatterTest.php @@ -60,6 +60,16 @@ public function testFormat(string $sql, string $html): void $this->assertEquals(trim($html), trim($formatter->format($sql))); } + public function testFormatUpperCase(): void + { + $formatter = new SqlFormatter(new NullHighlighter()); + + $actual = $formatter->format('select a from b where c = d;', ' ', true); + $expected = "SELECT\n a\nFROM\n b\nWHERE\n c = d;"; + + $this->assertEquals(trim($expected), trim($actual)); + } + /** * @dataProvider highlightData */