ConfirmationQuestion.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. * @return callable
  34. */
  35. private function getDefaultNormalizer()
  36. {
  37. $default = $this->getDefault();
  38. $regex = $this->trueAnswerRegex;
  39. return function ($answer) use ($default, $regex) {
  40. if (\is_bool($answer)) {
  41. return $answer;
  42. }
  43. $answerIsTrue = (bool) preg_match($regex, $answer);
  44. if (false === $default) {
  45. return $answer && $answerIsTrue;
  46. }
  47. return '' === $answer || $answerIsTrue;
  48. };
  49. }
  50. }