Version: current

     1 <?php
     2 /**
     3  * Format a SQL Query for better readable output in HTML or Plaintext.
     4  * Its a simple string parser, not a full tokenizer - so formatting
     5  * is not aware of the SQL syntax. This means we have to be conservative
     6  * with modifying the SQL string.
     7  *
     8  * @package sapphire
     9  * @subpackage parsers
    10  * @author Ingo Schommer, Silverstripe Ltd. (<firstname>@silverstripe.com)
    11  */
    12 class SQLFormatter extends Object {
    13
    14     protected static $newline_before_tokens = array(
    15         'SELECT',
    16         'UPDATE',
    17         'INSERT',
    18         'DELETE',
    19         'FROM',
    20         'INNER JOIN',
    21         'FULL JOIN',
    22         'LEFT JOIN',
    23         'RIGHT JOIN',
    24         'WHERE',
    25         'ORDER BY',
    26         'GROUP BY',
    27         'LIMIT',
    28     );
    29
    30     public function formatPlain($sql) {
    31         $sql = $this->addNewlines($sql, false);
    32
    33         return $sql;
    34     }
    35
    36     public function formatHTML($sql) {
    37         $sql = $this->addNewlines($sql, true);
    38
    39         return $sql;
    40     }
    41
    42     /**
    43      * Newlines for tokens defined in $newline_before_tokens.
    44      * Case-sensitive, only applies to uppercase SQL to avoid
    45      * messing with possible content fragments in the query.
    46      */
    47     protected function addNewlines($sql, $useHtmlFormatting = false) {
    48         $eol = PHP_EOL;
    49         foreach(self::$newline_before_tokens as $token) {
    50             $breakToken = ($useHtmlFormatting) ? "<br />$eol" : $eol;
    51             $sql = preg_replace('/[^\n](' . $token . ')/', $breakToken . '$1', $sql);
    52         }
    53
    54         return $sql;
    55     }
    56
    57 }
    58 ?>

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -