From 6ec22206418ca662226ffa14fa0aa238e966a7ea Mon Sep 17 00:00:00 2001 From: Tyler Bannister Date: Mon, 16 Jan 2023 10:24:35 -0500 Subject: [PATCH] Move the blocking check to the read method. Move the stream_get_meta_data check into the read function to always restore the original status. Also to prevent unnecessary looping/screen flicker, turn blocking off only when there is data in the internal stream buffer. --- src/IO/ResourceInputStream.php | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/src/IO/ResourceInputStream.php b/src/IO/ResourceInputStream.php index b3d02cb..cdf66df 100644 --- a/src/IO/ResourceInputStream.php +++ b/src/IO/ResourceInputStream.php @@ -17,11 +17,6 @@ class ResourceInputStream implements InputStream */ private $stream; - /** - * @var bool Original blocking state. - */ - private $blocking; - public function __construct($stream = \STDIN) { if (!is_resource($stream) || get_resource_type($stream) !== 'stream') { @@ -33,26 +28,17 @@ public function __construct($stream = \STDIN) throw new \InvalidArgumentException('Expected a readable stream'); } - $meta = stream_get_meta_data($stream); - $this->blocking = $meta['blocked']; $this->stream = $stream; } - /** - * Restore the blocking state. - */ - public function __destruct() { - stream_set_blocking($this->stream, $this->blocking); - } - public function read(int $numBytes, callable $callback) : void { - $buffer = fread($this->stream, $numBytes); - if (!empty($buffer)) { - // Prevent blocking to handle pasted input. + $meta = stream_get_meta_data($this->stream); + if ($meta['blocked'] && ($meta['unread_bytes'] > 0)) { stream_set_blocking($this->stream, false); - } else { - // Re-enable blocking when input has been handled. + } + $buffer = fread($this->stream, $numBytes); + if ($meta['blocked'] && ($meta['unread_bytes'] > 0)) { stream_set_blocking($this->stream, true); }