Skip to content

Commit

Permalink
[ BugFix ] Handle Failed Terminal Read Gracefully (#164)
Browse files Browse the repository at this point in the history
* tell phpunit to fail on E_WARNING

* add test

* check for empty string in TypedValue listener

* strengthen types

* continue loop is key is empty string
  • Loading branch information
ProjektGopher authored Sep 18, 2024
1 parent ba5cdc3 commit 99f74bd
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 3 deletions.
2 changes: 1 addition & 1 deletion phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.2/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true" backupStaticProperties="true">
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.2/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true" backupStaticProperties="true" failOnWarning="true">
<testsuites>
<testsuite name="Test Suite">
<directory suffix="Test.php">./tests</directory>
Expand Down
6 changes: 4 additions & 2 deletions src/Concerns/TypedValue.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@ protected function trackTypedValue(string $default = '', bool $submit = true, ?c
$this->cursorPosition = mb_strlen($this->typedValue);
}

$this->on('key', function ($key) use ($submit, $ignore, $allowNewLine) {
if ($key[0] === "\e" || in_array($key, [Key::CTRL_B, Key::CTRL_F, Key::CTRL_A, Key::CTRL_E])) {
$this->on('key', function (string $key) use ($submit, $ignore, $allowNewLine): void {
if ($key !== '' &&
($key[0] === "\e" || in_array($key, [Key::CTRL_B, Key::CTRL_F, Key::CTRL_A, Key::CTRL_E]))
) {
if ($ignore !== null && $ignore($key)) {
return;
}
Expand Down
9 changes: 9 additions & 0 deletions src/Prompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,15 @@ public function prompt(): mixed
public function runLoop(callable $callable): mixed
{
while (($key = static::terminal()->read()) !== null) {
/**
* If $key is an empty string, Terminal::read
* has failed. We can continue to the next
* iteration of the loop, and try again.
*/
if ($key === '') {
continue;
}

$result = $callable($key);

if ($result instanceof Result) {
Expand Down
8 changes: 8 additions & 0 deletions tests/Feature/TextPromptTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,11 @@

text('What is your name?');
})->throws(Exception::class, 'Cancelled.');

it('handles a failed terminal read gracefully', function () {
Prompt::fake(['', Key::ENTER]);

$result = text('What is your name?');

expect($result)->toBe('');
});

0 comments on commit 99f74bd

Please sign in to comment.