diff options
author | Jeremy Dorn <jeremy@jeremydorn.com> | 2013-06-12 20:56:09 -0700 |
---|---|---|
committer | Jeremy Dorn <jeremy@jeremydorn.com> | 2013-06-12 20:56:09 -0700 |
commit | 3c7983d6d638233ea8e0e7705a3a8f3e4921ca75 (patch) | |
tree | eb22ed4f7f26107be94eedcbeedcce16162b89ae /lib | |
parent | bd1f09133f6dbbe0713856910e58ea9480c2be58 (diff) | |
download | sql-formatter-3c7983d6d638233ea8e0e7705a3a8f3e4921ca75.zip sql-formatter-3c7983d6d638233ea8e0e7705a3a8f3e4921ca75.tar.gz sql-formatter-3c7983d6d638233ea8e0e7705a3a8f3e4921ca75.tar.bz2 |
Added new compress method. Fixes #41
Added test cases for CLI mode and compress method.
Bumped patch version.
Diffstat (limited to 'lib')
-rw-r--r-- | lib/SqlFormatter.php | 44 |
1 files changed, 43 insertions, 1 deletions
diff --git a/lib/SqlFormatter.php b/lib/SqlFormatter.php index fec46e3..3a511a7 100644 --- a/lib/SqlFormatter.php +++ b/lib/SqlFormatter.php @@ -9,7 +9,7 @@ * @copyright 2013 Jeremy Dorn * @license http://opensource.org/licenses/MIT * @link http://github.com/jdorn/sql-formatter - * @version 1.2.9 + * @version 1.2.10 */ class SqlFormatter { @@ -701,6 +701,48 @@ class SqlFormatter } /** + * Compress a query by collapsing white space and removing comments + * + * @param String $string The SQL string + * + * @return String The SQL string without comments + */ + public static function compress($string) + { + $result = ''; + + $tokens = self::tokenize($string); + + + $whitespace = true; + foreach ($tokens as $token) { + // Skip comment tokens + if ($token[self::TOKEN_TYPE] === self::TOKEN_TYPE_COMMENT || $token[self::TOKEN_TYPE] === self::TOKEN_TYPE_BLOCK_COMMENT) { + continue; + } + + if($token[self::TOKEN_TYPE] === self::TOKEN_TYPE_WHITESPACE) { + // If the last token was whitespace, don't add another one + if($whitespace) { + continue; + } + else { + $whitespace = true; + // Convert all whitespace to a single space + $token[self::TOKEN_VALUE] = ' '; + } + } + else { + $whitespace = false; + } + + $result .= $token[self::TOKEN_VALUE]; + } + + return rtrim($result); + } + + /** * Highlights a token depending on its type. * * @param Array $token An associative array containing type and value. |