From a9d6068c57652f8c5290d4668f1377387f308a76 Mon Sep 17 00:00:00 2001 From: fancyweb Date: Thu, 3 Jan 2019 10:35:51 +0100 Subject: [PATCH] feat(buffer-io): add the possibility to set user inputs for interactive questions --- src/Composer/IO/BufferIO.php | 24 ++++++++++++++ tests/Composer/Test/IO/BufferIOTest.php | 43 +++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 tests/Composer/Test/IO/BufferIOTest.php diff --git a/src/Composer/IO/BufferIO.php b/src/Composer/IO/BufferIO.php index d47d4eaa5..742c3f8a4 100644 --- a/src/Composer/IO/BufferIO.php +++ b/src/Composer/IO/BufferIO.php @@ -14,6 +14,7 @@ namespace Composer\IO; use Symfony\Component\Console\Output\StreamOutput; use Symfony\Component\Console\Formatter\OutputFormatterInterface; +use Symfony\Component\Console\Input\StreamableInputInterface; use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Helper\HelperSet; @@ -56,4 +57,27 @@ class BufferIO extends ConsoleIO return $output; } + + public function setUserInputs(array $inputs) + { + if (!$this->input instanceof StreamableInputInterface) { + throw new \RuntimeException('Setting the user inputs requires at least the version 3.2 of the symfony/console component.'); + } + + $this->input->setStream($this->createStream($inputs)); + $this->input->setInteractive(true); + } + + private function createStream(array $inputs) + { + $stream = fopen('php://memory', 'r+', false); + + foreach ($inputs as $input) { + fwrite($stream, $input.PHP_EOL); + } + + rewind($stream); + + return $stream; + } } diff --git a/tests/Composer/Test/IO/BufferIOTest.php b/tests/Composer/Test/IO/BufferIOTest.php new file mode 100644 index 000000000..013a3c100 --- /dev/null +++ b/tests/Composer/Test/IO/BufferIOTest.php @@ -0,0 +1,43 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Test\IO; + +use Composer\IO\BufferIO; +use Composer\Test\TestCase; +use Symfony\Component\Console\Input\StreamableInputInterface; + +class BufferIOTest extends TestCase +{ + public function testSetUserInputs() + { + $bufferIO = new BufferIO(); + + $refl = new \ReflectionProperty($bufferIO, 'input'); + $refl->setAccessible(true); + $input = $refl->getValue($bufferIO); + + if (!$input instanceof StreamableInputInterface) { + $this->setExpectedException('\RuntimeException', 'Setting the user inputs requires at least the version 3.2 of the symfony/console component.'); + } + + $bufferIO->setUserInputs(array( + 'yes', + 'no', + '', + )); + + $this->assertTrue($bufferIO->askConfirmation('Please say yes!', 'no')); + $this->assertFalse($bufferIO->askConfirmation('Now please say no!', 'yes')); + $this->assertSame('default', $bufferIO->ask('Empty string last', 'default')); + } +}