Skip to content

Commit

Permalink
Add uppercase auto-formatting as a passable option to the format meth…
Browse files Browse the repository at this point in the history
…od, ensuring the implementation is backwards compatible. Abstracted from the fork source PR jdorn/sql-formatter#86
  • Loading branch information
othyn committed Apr 8, 2021
1 parent acb59a3 commit b309a31
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/SqlFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function __construct(?Highlighter $highlighter = null)
*
* @return string The SQL string with HTML styles and formatting wrapped in a <pre> 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 = '';
Expand All @@ -71,9 +71,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
Expand Down
10 changes: 10 additions & 0 deletions tests/SqlFormatterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down

0 comments on commit b309a31

Please sign in to comment.