Last active
April 16, 2022 17:19
-
-
Save coisa/22faa5d8d393204ca5cbf6e4e84fb03c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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