Skip to content

Commit 975a0b8

Browse files
authored
Merge pull request #239 from staabm/stdin
Support reading from stdin
2 parents d500a21 + 67ca444 commit 975a0b8

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/Utils/CLI.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,11 @@ public function runHighlight()
7777

7878
return 0;
7979
}
80+
if (!isset($params['q'])) {
81+
if ($stdIn = $this->readStdin()) {
82+
$params['q'] = $stdIn;
83+
}
84+
}
8085
if (isset($params['q'])) {
8186
echo Formatter::format(
8287
$params['q'],
@@ -127,6 +132,11 @@ public function runLint()
127132
if (isset($params['c'])) {
128133
Context::load($params['c']);
129134
}
135+
if (!isset($params['q'])) {
136+
if ($stdIn = $this->readStdin()) {
137+
$params['q'] = $stdIn;
138+
}
139+
}
130140
if (isset($params['q'])) {
131141
$lexer = new Lexer($params['q'], false);
132142
$parser = new Parser($lexer->list);
@@ -177,6 +187,11 @@ public function runTokenize()
177187

178188
return 0;
179189
}
190+
if (!isset($params['q'])) {
191+
if ($stdIn = $this->readStdin()) {
192+
$params['q'] = $stdIn;
193+
}
194+
}
180195
if (isset($params['q'])) {
181196
$lexer = new Lexer($params['q'], false);
182197
foreach ($lexer->list->tokens as $idx => $token) {
@@ -199,4 +214,12 @@ public function runTokenize()
199214

200215
return 1;
201216
}
217+
218+
private function readStdin() {
219+
stream_set_blocking(STDIN, false);
220+
$stdin = stream_get_contents(STDIN);
221+
// restore-default block-mode setting
222+
stream_set_blocking(STDIN, true);
223+
return $stdin;
224+
}
202225
}

tests/Utils/CLITest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,4 +205,30 @@ public function tokenizeParams()
205205
],
206206
];
207207
}
208+
209+
/**
210+
* @dataProvider stdinParams
211+
*
212+
* @param string $cmd
213+
* @param int $result
214+
*/
215+
public function testStdinPipe($cmd, $result)
216+
{
217+
exec ($cmd, $out, $ret);
218+
$this->assertSame($result, $ret);
219+
}
220+
221+
public function stdinParams()
222+
{
223+
$binPath = PHP_BINARY .' '. dirname(__DIR__,2 ). '/bin/';
224+
225+
return [
226+
['echo "SELECT 1" | '. $binPath .'highlight-query', 0],
227+
['echo "invalid query" | '. $binPath .'highlight-query', 0],
228+
['echo "SELECT 1" | '. $binPath .'lint-query', 0],
229+
['echo "invalid query" | '. $binPath .'lint-query', 10],
230+
['echo "SELECT 1" | '. $binPath .'tokenize-query', 0],
231+
['echo "invalid query" | '. $binPath .'tokenize-query', 0],
232+
];
233+
}
208234
}

0 commit comments

Comments
 (0)