From eaec19ea3020c44d1e3dfc6b8adaac47a4e47569 Mon Sep 17 00:00:00 2001 From: Daniil Gentili Date: Mon, 15 Jul 2019 16:16:07 +0200 Subject: [PATCH] Add async readline/echo and add composer commands --- composer.json | 9 ++++++++ examples/gzip-compress.php | 10 ++++----- examples/gzip-decompress.php | 10 ++++----- examples/readline-echo.php | 18 ++++++++++++++++ lib/functions.php | 36 +++++++++++++++++++++++++++++++ test/ResourceOutputStreamTest.php | 20 +++++++++++++++++ 6 files changed, 93 insertions(+), 10 deletions(-) create mode 100644 examples/readline-echo.php diff --git a/composer.json b/composer.json index 71d7330..2dfc284 100644 --- a/composer.json +++ b/composer.json @@ -52,5 +52,14 @@ "platform": { "php": "7.0.0" } + }, + "scripts": { + "check": [ + "@cs", + "@test" + ], + "cs": "PHP_CS_FIXER_IGNORE_ENV=1 php-cs-fixer fix -v --diff --dry-run", + "cs-fix": "PHP_CS_FIXER_IGNORE_ENV=1 php-cs-fixer fix -v --diff", + "test": "@php -dzend.assertions=1 -dassert.exception=1 ./vendor/bin/phpunit --coverage-text" } } diff --git a/examples/gzip-compress.php b/examples/gzip-compress.php index c45279b..f96feb2 100644 --- a/examples/gzip-compress.php +++ b/examples/gzip-compress.php @@ -1,15 +1,15 @@ write($prompt); + } + static $lines = ['']; + while (\count($lines) < 2 && ($chunk = yield $stdin->read()) !== null) { + $chunk = \explode("\n", \str_replace(["\r", "\n\n"], "\n", $chunk)); + $lines[\count($lines) - 1] .= \array_shift($chunk); + $lines = \array_merge($lines, $chunk); + } + return \array_shift($lines); + }); +} + +/** + * Simple wrapper function to asynchronously write a string to the PHP output buffer. + * + * @param string $string + * @return Promise + */ +function bufferEcho($string): Promise +{ + return getOutputBufferStream()->write($string); +} diff --git a/test/ResourceOutputStreamTest.php b/test/ResourceOutputStreamTest.php index e186e12..25a33c5 100644 --- a/test/ResourceOutputStreamTest.php +++ b/test/ResourceOutputStreamTest.php @@ -4,7 +4,9 @@ namespace Amp\ByteStream\Test; use Amp\ByteStream\ResourceOutputStream; use Amp\ByteStream\StreamException; +use Amp\Loop; use PHPUnit\Framework\TestCase; +use function Amp\ByteStream\bufferEcho; use function Amp\Promise\wait; class ResourceOutputStreamTest extends TestCase @@ -66,4 +68,22 @@ class ResourceOutputStreamTest extends TestCase wait($stream->write("foobar")); wait($stream->write("foobar")); } + + public function testEcho() + { + Loop::run(function () { + $data = "\n".\base64_encode(\random_bytes(10))."\n"; + $found = false; + \ob_start(static function ($match) use (&$found, $data) { + if ($match === $data) { + $found = true; + return ''; + } + return $match; + }); + yield bufferEcho($data); + \ob_end_flush(); + $this->assertTrue($found, "Data wasn't sent to the output buffer"); + }); + } }