Skip to content

Commit

Permalink
Fix phar-io#218: Error when we are unable to read CLI input
Browse files Browse the repository at this point in the history
- Add protection for non-interactive shell (or any error from fgets)
  • Loading branch information
MacFJA committed Apr 19, 2020
1 parent b97a569 commit bb7021d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/shared/cli/input/ConsoleInput.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,13 @@ public function confirm(string $message, bool $default = true): bool {

do {
$this->output->writeText(\rtrim($message) . \sprintf(' [%s|%s] ', $yesOption, $noOption));
$response = \strtolower(\rtrim(\fgets($this->inputStream)));
$input = \fgets($this->inputStream);

if ($input === false) {
throw new RunnerException('Needs tty to be able to confirm');
}

$response = \strtolower(\rtrim($input));
} while (!\in_array($response, ['y', 'n', ''], true));

if ($response === '') {
Expand Down
22 changes: 22 additions & 0 deletions tests/unit/shared/cli/ConsoleInputTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use PharIo\Phive\Cli\ConsoleInput;
use PharIo\Phive\Cli\Output;
use PharIo\Phive\Cli\RunnerException;
use PHPUnit\Framework\TestCase;

/**
Expand Down Expand Up @@ -86,6 +87,27 @@ public function testReturnsDefaultOnEnter($default): void {
$this->assertSame($default, $input->confirm('foo?', $default));
}

public function testOnNonInteractive(): void {
$output = $this->getOutputMock();
$output->expects($this->once())
->method('writeText')
->with('foo? [Y|n] ');

/*
* Emulate a non-interactive shell by not writing anything
*
* In a real shell it can be emulate with `echo -n | phive install ...`
*/
$inputStream = \fopen('php://memory', 'r');

$input = new ConsoleInput($output, $inputStream);

$this->expectException(RunnerException::class);
$this->expectExceptionMessage('Needs tty to be able to confirm');

$input->confirm('foo?');
}

/**
* @return Output|\PHPUnit_Framework_MockObject_MockObject
*/
Expand Down

0 comments on commit bb7021d

Please sign in to comment.