From 0a89fc07917b0f2023a68e0a5ad6a83bde302b7a Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sat, 24 Oct 2026 12:54:01 +0200 Subject: [PATCH] Retry partial writes in ResourceOutputStream ResourceInputStream switches STDIN to non-blocking after reading input so pasted text can be read in one go. On a TTY, STDIN and STDOUT share a file description, so STDOUT becomes non-blocking too and fwrite can write only part of a large buffer. cli-menu redraws were truncated after the first keypress, garbling the menu. Keep writing until the whole buffer is out. --- src/IO/ResourceOutputStream.php | 10 ++++++- test/IO/PartialWriteStream.php | 42 ++++++++++++++++++++++++++++ test/IO/ResourceOutputStreamTest.php | 15 ++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 test/IO/PartialWriteStream.php diff --git a/src/IO/ResourceOutputStream.php b/src/IO/ResourceOutputStream.php index 07b5ba8..8a86dce 100644 --- a/src/IO/ResourceOutputStream.php +++ b/src/IO/ResourceOutputStream.php @@ -36,7 +36,15 @@ public function __construct($stream = \STDOUT) public function write(string $buffer): void { - fwrite($this->stream, $buffer); + // The stream may be non-blocking (on a TTY it shares a file description with STDIN, + // which ResourceInputStream makes non-blocking), so fwrite can write only part of the buffer + while ($buffer !== '') { + $written = fwrite($this->stream, $buffer); + if ($written === false) { + return; + } + $buffer = substr($buffer, $written); + } } /** diff --git a/test/IO/PartialWriteStream.php b/test/IO/PartialWriteStream.php new file mode 100644 index 0000000..54abdf2 --- /dev/null +++ b/test/IO/PartialWriteStream.php @@ -0,0 +1,42 @@ +full = !$this->full; + if (!$this->full) { + return 0; + } + + $chunk = substr($data, 0, 2); + self::$contents .= $chunk; + return strlen($chunk); + } + + // phpcs:ignore PSR1.Methods.CamelCapsMethodName + public function stream_eof(): bool + { + return false; + } +} diff --git a/test/IO/ResourceOutputStreamTest.php b/test/IO/ResourceOutputStreamTest.php index 7a61772..c9fb124 100644 --- a/test/IO/ResourceOutputStreamTest.php +++ b/test/IO/ResourceOutputStreamTest.php @@ -33,4 +33,19 @@ public function testWrite(): void rewind($stream); static::assertEquals('123456789', stream_get_contents($stream)); } + + public function testWriteRetriesPartialWrites(): void + { + stream_wrapper_register('partial', PartialWriteStream::class); + + try { + $stream = fopen('partial://test', 'w'); + $outputStream = new ResourceOutputStream($stream); + $outputStream->write('123456789'); + + static::assertEquals('123456789', PartialWriteStream::$contents); + } finally { + stream_wrapper_unregister('partial'); + } + } }