Skip to content

Commit

Permalink
Simplify buffer function
Browse files Browse the repository at this point in the history
This avoids the extra Deferred and directly uses reject instead.
  • Loading branch information
kelunik committed Oct 24, 2017
1 parent 1503761 commit 0be5dbb
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,18 @@ function buffer(ReadableStreamInterface $stream, $maxLength = null)
return Promise\resolve('');
}

$deferred = new Promise\Deferred();
$buffer = '';
$bufferer = function ($data) use (&$buffer, $deferred, $maxLength) {
$buffer .= $data;
if ($maxLength !== null && isset($buffer[$maxLength])) {
$deferred->reject(new \OverflowException('Buffer exceeded maximum length'));
}
};
$stream->on('data', $bufferer);
$buffer = '';

$promise = new Promise\Promise(function ($resolve, $reject) use ($stream, $maxLength, &$buffer, &$bufferer) {
$bufferer = function ($data) use (&$buffer, $reject, $maxLength) {
$buffer .= $data;

if ($maxLength !== null && isset($buffer[$maxLength])) {
$reject(new \OverflowException('Buffer exceeded maximum length'));
}
};

$promise = new Promise\Promise(function ($resolve, $reject) use ($stream, $deferred, &$buffer) {
$deferred->promise()->then($resolve, $reject);
$stream->on('data', $bufferer);

$stream->on('error', function ($error) use ($reject) {
$reject(new \RuntimeException('An error occured on the underlying stream while buffering', 0, $error));
Expand Down

0 comments on commit 0be5dbb

Please # to comment.