Skip to content

Commit

Permalink
Fix retrywrapper when the wrapped stream fails to write or read compl…
Browse files Browse the repository at this point in the history
…etely
  • Loading branch information
icewind1991 committed Jun 2, 2016
1 parent 9ca4027 commit d3620e8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/RetryWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public function stream_read($count) {
$result = parent::stream_read($count);

$bytesReceived = strlen($result);
while ($bytesReceived < $count && !$this->stream_eof()) {
while (strlen($result) > 0 && $bytesReceived < $count && !$this->stream_eof()) {
$result .= parent::stream_read($count - $bytesReceived);
$bytesReceived = strlen($result);
}
Expand All @@ -54,11 +54,13 @@ public function stream_read($count) {

public function stream_write($data) {
$bytesToSend = strlen($data);
$result = parent::stream_write($data);
$bytesWritten = parent::stream_write($data);
$result = $bytesWritten;

while ($result < $bytesToSend && !$this->stream_eof()) {
while ($bytesWritten > 0 && $result < $bytesToSend && !$this->stream_eof()) {
$dataLeft = substr($data, $result);
$result += parent::stream_write($dataLeft);
$bytesWritten = parent::stream_write($dataLeft);
$result += $bytesWritten;
}

return $result;
Expand Down
38 changes: 38 additions & 0 deletions tests/RetryWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,32 @@ public function stream_write($data) {
}
}

class FailWrapper extends \Icewind\Streams\NullWrapper {
/**
* Wraps a stream with the provided callbacks
*
* @param resource $source
* @return resource
*
* @throws \BadMethodCallException
*/
public static function wrap($source) {
$context = stream_context_create(array(
'null' => array(
'source' => $source)
));
return self::wrapSource($source, $context, 'fail', '\Icewind\Streams\Tests\FailWrapper');
}

public function stream_read($count) {
return false;
}

public function stream_write($data) {
return false;
}
}

class RetryWrapper extends Wrapper {

/**
Expand All @@ -52,4 +78,16 @@ public function testReadDir() {
public function testRewindDir() {
$this->markTestSkipped('directories not supported');
}

public function testFailedRead() {
$source = fopen('data://text/plain,foo', 'r');
$wrapped = \Icewind\Streams\RetryWrapper::wrap(FailWrapper::wrap($source));
$this->assertEquals('', fread($wrapped, 10));
}

public function testFailedWrite() {
$source = fopen('php://temp', 'w');
$wrapped = \Icewind\Streams\RetryWrapper::wrap(FailWrapper::wrap($source));
fwrite($wrapped, 'foo');
}
}

0 comments on commit d3620e8

Please sign in to comment.