Преглед на файлове

feat(buffer-io): add the possibility to set user inputs for interactive questions

fancyweb преди 6 години
родител
ревизия
a9d6068c57
променени са 2 файла, в които са добавени 67 реда и са изтрити 0 реда
  1. 24 0
      src/Composer/IO/BufferIO.php
  2. 43 0
      tests/Composer/Test/IO/BufferIOTest.php

+ 24 - 0
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;
+    }
 }

+ 43 - 0
tests/Composer/Test/IO/BufferIOTest.php

@@ -0,0 +1,43 @@
+<?php
+
+/*
+ * This file is part of Composer.
+ *
+ * (c) Nils Adermann <naderman@naderman.de>
+ *     Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * 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'));
+    }
+}