Add method to get a readable stream of a file

This commit is contained in:
Robin Appelman 2014-07-12 15:51:16 +02:00
commit eca03d1b88
4 changed files with 53 additions and 1 deletions

View file

@ -76,8 +76,10 @@ class Connection extends RawConnection {
} }
public function close() { public function close() {
if (is_resource($this->getInputStream())) {
$this->write('close' . PHP_EOL); $this->write('close' . PHP_EOL);
} }
}
public function __destruct() { public function __destruct() {
$this->close(); $this->close();

View file

@ -85,6 +85,14 @@ class RawConnection {
return $output; return $output;
} }
public function getOutputStream() {
return $this->pipes[1];
}
public function getInputStream() {
return $this->pipes[0];
}
public function __destruct() { public function __destruct() {
proc_terminate($this->process); proc_terminate($this->process);
proc_close($this->process); proc_close($this->process);

View file

@ -50,6 +50,11 @@ class Share {
} }
} }
/**
* Get the name of the share
*
* @return string
*/
public function getName() { public function getName() {
return $this->name; return $this->name;
} }
@ -185,6 +190,28 @@ class Share {
return $this->parseOutput($output); return $this->parseOutput($output);
} }
/**
* Open a readable stream top a remote file
*
* @param string $source
* @return resource a read only stream with the contents of the remote file
*/
public function read($source) {
$source = $this->escapePath($source);
// since we do binary transfer over STDOUT we create a new connection
$command = Server::CLIENT . ' -U ' . escapeshellarg($this->server->getUser()) .
' //' . $this->server->getHost() . '/' . $this->name
. ' -c \'get ' . $source . ' -\'';
$connection = new Connection($command, array(
'PASSWD' => $this->server->getPassword()
));
$fh = $connection->getOutputStream();
//save the connection as context of the stream to prevent it going out of scope and cleaning up the resource
stream_context_set_option($fh, 'file', 'connection', $connection);
return $fh;
}
/** /**
* @return Server * @return Server
*/ */

View file

@ -282,4 +282,19 @@ class Share extends \PHPUnit_Framework_TestCase {
$this->assertTrue(abs($now - $mtime) <= 1, 'Modified time differs by ' . abs($now - $mtime) . ' seconds'); $this->assertTrue(abs($now - $mtime) <= 1, 'Modified time differs by ' . abs($now - $mtime) . ' seconds');
$this->share->del($this->root . '/foo.txt'); $this->share->del($this->root . '/foo.txt');
} }
public function testListRoot() {
$files = $this->share->dir('');
$this->assertGreaterThan(0, count($files));
}
public function testReadStream() {
$sourceFile = $this->getTextFile();
$this->share->put($sourceFile, $this->root . '/foobar');
$fh = $this->share->read($this->root . '/foobar');
$content = stream_get_contents($fh);
$this->share->del($this->root . '/foobar');
$this->assertEquals(file_get_contents($sourceFile), $content);
}
} }