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'); + } + } }