{
protected $renderer;
+ protected $format = false;
+ protected $colors = false;
+
/**
* Start processing.
*
$allfine = true;
foreach ($files as $filename) {
- $allfine &= $this->checkFile($filename);
+ if ($this->format) {
+ $allfine &= $this->formatFile($filename);
+ } else {
+ $allfine &= $this->checkFile($filename);
+ }
}
if ($allfine == true) {
public function checkFile($filename)
{
$this->renderer->startRendering($filename);
-
- if ($filename == '-') {
- $sql = file_get_contents('php://stdin');
- } else {
- $sql = file_get_contents($filename);
- }
- if (trim($sql) == '') {
- $this->renderer->displayError('SQL file empty', '', 0, 0);
+ $sql = $this->loadSql($filename);
+ if ($sql === false) {
return false;
}
return false;
}
+ /**
+ * Reformat the given file
+ */
+ protected function formatFile($filename)
+ {
+ $this->renderer->startRendering($filename);
+ $sql = $this->loadSql($filename);
+ if ($sql === false) {
+ return false;
+ }
+
+ $options = array(
+ //FIXME: automatically detect if the shell/tool supports colors
+ 'type' => $this->colors ? 'cli' : 'text'
+ );
+ echo \SqlParser\Utils\Formatter::format($sql, $options) . "\n";
+ }
+
+ protected function loadSql($filename)
+ {
+ if ($filename == '-') {
+ $sql = file_get_contents('php://stdin');
+ } else {
+ $sql = file_get_contents($filename);
+ }
+ if (trim($sql) == '') {
+ $this->renderer->displayError('SQL file empty', '', 0, 0);
+ return false;
+ }
+ return $sql;
+ }
+
/**
* Load parameters for the CLI option parser.
*
$parser->version = '0.0.2';
$parser->avoid_reading_stdin = true;
+ $parser->addOption(
+ 'format',
+ array(
+ 'short_name' => '-f',
+ 'long_name' => '--format',
+ 'description' => 'Reformat SQL instead of checking',
+ 'action' => 'StoreTrue',
+ 'default' => false,
+ )
+ );
+ $parser->addOption(
+ 'colors',
+ array(
+ 'long_name' => '--color',
+ 'description' => 'Use colors in formatting output',
+ 'action' => 'StoreTrue',
+ )
+ );
+ $parser->addOption(
+ 'nocolors',
+ array(
+ 'long_name' => '--nocolor',
+ 'description' => 'Disable colors in formatting output',
+ 'action' => 'StoreTrue',
+ )
+ );
$parser->addOption(
'renderer',
array(
. ucfirst($result->options['renderer']);
$this->renderer = new $rendClass();
+ $this->format = $result->options['format'];
+
+ if ($result->options['colors'] !== null) {
+ $this->colors = $result->options['colors'];
+ } else if ($result->options['nocolors'] !== null) {
+ $this->colors = !$result->options['nocolors'];
+ } else {
+ //default coloring to enabled, except
+ // when piping | to another tool
+ $this->colors = true;
+ if (function_exists('posix_isatty')
+ && !posix_isatty(STDOUT)
+ ) {
+ $this->colors = false;
+ }
+ }
+
foreach ($result->args['sql_files'] as $filename) {
if ($filename == '-') {
continue;