You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.5 KiB

3 years ago
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Question;
  11. /**
  12. * Represents a yes/no question.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class ConfirmationQuestion extends Question
  17. {
  18. private $trueAnswerRegex;
  19. /**
  20. * @param string $question The question to ask to the user
  21. * @param bool $default The default answer to return, true or false
  22. * @param string $trueAnswerRegex A regex to match the "yes" answer
  23. */
  24. public function __construct(string $question, bool $default = true, string $trueAnswerRegex = '/^y/i')
  25. {
  26. parent::__construct($question, $default);
  27. $this->trueAnswerRegex = $trueAnswerRegex;
  28. $this->setNormalizer($this->getDefaultNormalizer());
  29. }
  30. /**
  31. * Returns the default answer normalizer.
  32. */
  33. private function getDefaultNormalizer(): callable
  34. {
  35. $default = $this->getDefault();
  36. $regex = $this->trueAnswerRegex;
  37. return function ($answer) use ($default, $regex) {
  38. if (\is_bool($answer)) {
  39. return $answer;
  40. }
  41. $answerIsTrue = (bool) preg_match($regex, $answer);
  42. if (false === $default) {
  43. return $answer && $answerIsTrue;
  44. }
  45. return '' === $answer || $answerIsTrue;
  46. };
  47. }
  48. }