Skip to content

Instantly share code, notes, and snippets.

@coisa
Last active April 16, 2022 17:19
Show Gist options
  • Save coisa/22faa5d8d393204ca5cbf6e4e84fb03c to your computer and use it in GitHub Desktop.
Save coisa/22faa5d8d393204ca5cbf6e4e84fb03c to your computer and use it in GitHub Desktop.
<?php
namespace CoiSA\Helper;
final class ReadlineAllowedAnswers
{
public function __construct(
private string $question,
private array $allowedAnswers = ['y', 'n'],
private bool $isCaseSensitive = false
) {
if ($isCaseSensitive) {
$this->allowedAnswers = array_map('strtolower', $this->allowedAnswers);
}
}
public function promptAnswer(): string
{
try {
$answer = readline($this->question);
if (false === $this->isCaseSensitive) {
$answer = strtolower($answer);
}
$isValidAnswer = in_array($answer, $this->allowedAnswers);
if (false === $isValidAnswer) {
throw new UnexpectedValueException('Answer not allowed!');
}
} catch (Throwable $exception) {
echo $exception->getMessage() . PHP_EOL;
return $this->promptAnswer();
}
return $answer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment