9 * @author Christian Weiske <cweiske@cweiske.de>
10 * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3
11 * @link http://cweiske.de/php-sqllint.htm
16 require_once 'Console/CommandLine.php';
19 * Command line interface
22 * @package PHP-SQLlint
23 * @author Christian Weiske <cweiske@cweiske.de>
24 * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3
25 * @link http://www.emacswiki.org/emacs/CreatingYourOwnCompileErrorRegexp
39 $parser = $this->loadParameters();
40 $files = $this->parseParameters($parser);
43 foreach ($files as $filename) {
44 $allfine &= $this->checkFile($filename);
47 if ($allfine == true) {
52 } catch (\Exception $e) {
53 echo 'Error: ' . $e->getMessage() . "\n";
59 * Check a .sql file for syntax errors
61 * @param string $filename File path
63 * @return boolean True if there were no errors, false if there were some
65 public function checkFile($filename)
67 $this->renderer->startRendering($filename);
69 $sql = file_get_contents($filename);
70 if (trim($sql) == '') {
71 $this->renderer->displayError('SQL file empty', '', 0, 0);
75 $parser = new \SqlParser\Parser($sql);
76 if (count($parser->errors) == 0) {
77 $this->renderer->finishOk();
81 $lines = array(1 => 0);
84 while (false !== $pos = strpos($sql, "\n", ++$pos)) {
85 $lines[++$line] = $pos;
88 foreach ($parser->errors as $error) {
89 /* @var SqlParser\Exceptions\ParserException $error) */
92 while (next($lines) && $error->token->position >= current($lines)) {
95 $col = $error->token->position - $lines[$line];
97 $this->renderer->displayError(
99 //FIXME: ->token or ->value?
100 $error->token->token,
110 * Load parameters for the CLI option parser.
112 * @return \Console_CommandLine CLI option parser
114 protected function loadParameters()
116 $parser = new \Console_CommandLine();
117 $parser->description = 'php-sqllint';
118 $parser->version = '0.0.1';
123 'short_name' => '-r',
124 'long_name' => '--renderer',
125 'description' => 'Output mode',
126 'action' => 'StoreString',
132 'add_list_option' => true,
136 $parser->addArgument(
147 * Let the CLI option parser parse the options.
149 * @param object $parser Option parser
151 * @return array Array of file names
153 protected function parseParameters(\Console_CommandLine $parser)
156 $result = $parser->parse();
158 $rendClass = '\\phpsqllint\\Renderer_'
159 . ucfirst($result->options['renderer']);
160 $this->renderer = new $rendClass();
162 foreach ($result->args['sql_files'] as $filename) {
163 if (!file_exists($filename)) {
164 throw new \Exception('File does not exist: ' . $filename);
166 if (!is_file($filename)) {
167 throw new \Exception('Not a file: ' . $filename);
171 return $result->args['sql_files'];
172 } catch (\Exception $exc) {
173 $parser->displayError($exc->getMessage());