Skip to content

Commit 6967e04

Browse files
committed
Support explicitly closing STDOUT
1 parent d699901 commit 6967e04

File tree

4 files changed

+49
-2
lines changed

4 files changed

+49
-2
lines changed

src/Stdio.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public function __construct(LoopInterface $loop, ReadableStreamInterface $input
2626
}
2727

2828
if ($output === null) {
29-
$output = new Stdout(STDOUT);
29+
$output = new Stdout();
3030
}
3131

3232
if ($readline === null) {

src/Stdout.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,21 @@
66

77
class Stdout extends WritableStream
88
{
9+
public function __construct()
10+
{
11+
// STDOUT not defined ("php -a") or already closed (`fclose(STDOUT)`)
12+
if (!defined('STDOUT') || !is_resource(STDOUT)) {
13+
return $this->close();
14+
}
15+
}
16+
917
public function write($data)
1018
{
11-
// TODO: use non-blocking output instead
19+
if ($this->closed) {
20+
return false;
21+
}
1222

23+
// TODO: use non-blocking output instead
1324
fwrite(STDOUT, $data);
1425

1526
return true;

tests/FunctionalExampleTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,26 @@ public function testStubCanCloseStdinAndIsNotReadable()
5555
$this->assertContains('NO', $output);
5656
}
5757

58+
public function testStubCanCloseStdoutAndIsNotWritable()
59+
{
60+
$output = $this->execExample('php ../tests/stub/03-close-stdout.php 2>&1');
61+
62+
$this->assertEquals('', $output);
63+
}
64+
65+
public function testPeriodicExampleViaInteractiveModeQuitsImmediately()
66+
{
67+
if (defined('HHVM_VERSION')) {
68+
$this->markTestSkipped('Skipped interactive mode on HHVM');
69+
}
70+
71+
$output = $this->execExample('echo "require(\"01-periodic.php\");" | php -a');
72+
73+
// starts with either "Interactive mode enabled" or "Interactive shell"
74+
$this->assertStringStartsWith('Interactive ', $output);
75+
$this->assertNotContains('you just said:', $output);
76+
}
77+
5878
private function execExample($command)
5979
{
6080
chdir(__DIR__ . '/../examples/');

tests/stub/03-close-stdout.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
use Clue\React\Stdio\Stdio;
4+
5+
require __DIR__ . '/../../vendor/autoload.php';
6+
7+
$loop = React\EventLoop\Factory::create();
8+
9+
fclose(STDOUT);
10+
$stdio = new Stdio($loop);
11+
if ($stdio->isWritable()) {
12+
throw new \RuntimeException('Not writable');
13+
}
14+
$stdio->close();
15+
16+
$loop->run();

0 commit comments

Comments
 (0)