ConfirmationQuestion.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. /**
  19. * @param string $question The question to ask to the user
  20. * @param bool $default The default answer to return, true or false
  21. * @param string $trueAnswerRegex A regex to match the "yes" answer
  22. */
  23. public function __construct(
  24. string $question,
  25. bool $default = true,
  26. private string $trueAnswerRegex = '/^y/i',
  27. ) {
  28. parent::__construct($question, $default);
  29. $this->setNormalizer($this->getDefaultNormalizer());
  30. }
  31. /**
  32. * Returns the default answer normalizer.
  33. */
  34. private function getDefaultNormalizer(): callable
  35. {
  36. $default = $this->getDefault();
  37. $regex = $this->trueAnswerRegex;
  38. return function ($answer) use ($default, $regex) {
  39. if (\is_bool($answer)) {
  40. return $answer;
  41. }
  42. $answerIsTrue = (bool) preg_match($regex, $answer);
  43. if (false === $default) {
  44. return $answer && $answerIsTrue;
  45. }
  46. return '' === $answer || $answerIsTrue;
  47. };
  48. }
  49. }