Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/IO/ResourceOutputStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

/**
Expand Down
42 changes: 42 additions & 0 deletions test/IO/PartialWriteStream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace PhpSchool\TerminalTest\IO;

/**
* Alternates between accepting 2 bytes and accepting nothing, like a full non-blocking TTY
*/
class PartialWriteStream
{
public static string $contents = '';

private bool $full = false;

/** @var resource|null */
public $context;

// phpcs:ignore PSR1.Methods.CamelCapsMethodName
public function stream_open(string $path, string $mode): bool
{
self::$contents = '';
return true;
}

// phpcs:ignore PSR1.Methods.CamelCapsMethodName
public function stream_write(string $data): int
{
$this->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;
}
}
15 changes: 15 additions & 0 deletions test/IO/ResourceOutputStreamTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
}
}
Loading