From d8cc314d627d47b8d2fa98b4844e73621db039e7 Mon Sep 17 00:00:00 2001 From: Daniil Gentili Date: Mon, 3 Jun 2019 23:01:43 +0200 Subject: [PATCH] Add web SAPI input/output stream getter functions (#61) --- lib/functions.php | 37 +++++++++++++++++++++++++++++++++++++ test/StdStreamTest.php | 16 ++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/lib/functions.php b/lib/functions.php index c69fda9..a628fcc 100644 --- a/lib/functions.php +++ b/lib/functions.php @@ -62,6 +62,43 @@ function buffer(InputStream $source): Promise }); } +/** + * The php://input input buffer stream for the process associated with the currently active event loop. + * + * @return ResourceInputStream + */ +function getInputBufferStream(): ResourceInputStream +{ + static $key = InputStream::class . '\\input'; + + $stream = Loop::getState($key); + + if (!$stream) { + $stream = new ResourceInputStream(\fopen('php://input', 'r')); + Loop::setState($key, $stream); + } + + return $stream; +} + +/** + * The php://output output buffer stream for the process associated with the currently active event loop. + * + * @return ResourceOutputStream + */ +function getOutputBufferStream(): ResourceOutputStream +{ + static $key = OutputStream::class . '\\output'; + + $stream = Loop::getState($key); + + if (!$stream) { + $stream = new ResourceOutputStream(\fopen('php://output', 'w')); + Loop::setState($key, $stream); + } + + return $stream; +} /** * The STDIN stream for the process associated with the currently active event loop. * diff --git a/test/StdStreamTest.php b/test/StdStreamTest.php index b5f90ca..793969e 100644 --- a/test/StdStreamTest.php +++ b/test/StdStreamTest.php @@ -8,6 +8,22 @@ class StdStreamTest extends TestCase { + public function testGetInputBufferStream() + { + Loop::run(function () { + $stream = ByteStream\getInputBufferStream(); + $this->assertSame($stream, ByteStream\getInputBufferStream()); + }); + } + + public function testGetOutputBufferStream() + { + Loop::run(function () { + $stream = ByteStream\getOutputBufferStream(); + $this->assertSame($stream, ByteStream\getOutputBufferStream()); + }); + } + public function testGetStdin() { Loop::run(function () {