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