Skip to content

Commit 727e214

Browse files
authored
Merge pull request #30 from Arzaroth/master
Allow stdin to be a stream
2 parents a0c445a + 16d9bc5 commit 727e214

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

src/Command.php

+12-5
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ class Command
6060
public $locale;
6161

6262
/**
63-
* @var string to pipe to standard input
63+
* @var null|string|resource to pipe to standard input
6464
*/
6565
protected $_stdIn;
6666

@@ -159,7 +159,7 @@ public function setCommand($command)
159159
} elseif (isset($command[2]) && $command[2]===':') {
160160
$position = 2;
161161
} else {
162-
$position = false;
162+
$position = false;
163163
}
164164

165165
// Absolute path. If it's a relative path, let it slide.
@@ -172,8 +172,10 @@ public function setCommand($command)
172172
}
173173

174174
/**
175-
* @param string $stdIn If set, the string will be piped to the command via standard input.
175+
* @param string|resource $stdIn If set, the string will be piped to the command via standard input.
176176
* This enables the same functionality as piping on the command line.
177+
* It can also be a resource like a file handle or a stream in which case its content will be piped
178+
* into the command like an input redirection.
177179
* @return static for method chaining
178180
*/
179181
public function setStdIn($stdIn) {
@@ -345,8 +347,13 @@ public function execute()
345347

346348
if (is_resource($process)) {
347349

348-
if($this->_stdIn!==null) {
349-
fwrite($pipes[0], $this->_stdIn);
350+
if ($this->_stdIn!==null) {
351+
if (is_resource($this->_stdIn) &&
352+
in_array(get_resource_type($this->_stdIn), array('file', 'stream'), true)) {
353+
stream_copy_to_stream($this->_stdIn, $pipes[0]);
354+
} else {
355+
fwrite($pipes[0], $this->_stdIn);
356+
}
350357
fclose($pipes[0]);
351358
}
352359
$this->_stdOut = stream_get_contents($pipes[1]);

tests/CommandTest.php

+13
Original file line numberDiff line numberDiff line change
@@ -233,5 +233,18 @@ public function testCanRunCommandWithStandardInput()
233233
$this->assertTrue($command->getExecuted());
234234
$this->assertEquals("^I", $command->getOutput());
235235
}
236+
public function testCanRunCommandWithStandardInputStream()
237+
{
238+
$tmpfile = tmpfile();
239+
fwrite($tmpfile, "\t");
240+
fseek($tmpfile, 0);
241+
$command = new Command('/bin/cat');
242+
$command->addArg('-T');
243+
$command->setStdIn($tmpfile);
244+
$this->assertTrue($command->execute());
245+
$this->assertTrue($command->getExecuted());
246+
$this->assertEquals("^I", $command->getOutput());
247+
fclose($tmpfile);
248+
}
236249

237250
}

0 commit comments

Comments
 (0)