Skip to content

Commit

Permalink
Set/restore error handler within each loop iteration
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed May 1, 2020
1 parent 0dd0eb8 commit 2372142
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions lib/ResourceOutputStream.php
Expand Up @@ -62,13 +62,6 @@ public function __construct($stream, int $chunkSize = null)
$this->watcher = Loop::onWritable($stream, static function ($watcher, $stream) use ($writes, &$chunkSize, &$writable, &$resource) {
$firstWrite = true;

// Using error handler to verify that a write of zero bytes was not due an error.
// @see https://github.com/reactphp/stream/pull/150
$error = 0;
\set_error_handler(static function (int $errno) use (&$error) {
$error = $errno;
});

try {
while (!$writes->isEmpty()) {
/** @var Deferred $deferred */
Expand All @@ -84,6 +77,13 @@ public function __construct($stream, int $chunkSize = null)
throw new ClosedException("The stream was closed by the peer");
}

// Using error handler to verify that a write of zero bytes was not due an error.
// @see https://github.com/reactphp/stream/pull/150
$error = 0;
\set_error_handler(static function (int $errno) use (&$error) {
$error = $errno;
});

// Error reporting suppressed since fwrite() emits E_WARNING if the pipe is broken or the buffer is full.
// Use conditional, because PHP doesn't like getting null passed
if ($chunkSize) {
Expand All @@ -92,6 +92,8 @@ public function __construct($stream, int $chunkSize = null)
$written = @\fwrite($stream, $data);
}

\restore_error_handler();

\assert(
$written !== false || \PHP_VERSION_ID >= 70400, // PHP 7.4+ returns false on EPIPE.
"Trying to write on a previously fclose()'d resource. Do NOT manually fclose() resources the still referenced in the loop."
Expand Down Expand Up @@ -144,8 +146,6 @@ public function __construct($stream, int $chunkSize = null)
if ($writes->isEmpty()) {
Loop::disable($watcher);
}

\restore_error_handler();
}
});

Expand Down

0 comments on commit 2372142

Please sign in to comment.