Confirmation.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\console\output\question;
  12. use think\console\output\Question;
  13. class Confirmation extends Question
  14. {
  15. private $trueAnswerRegex;
  16. /**
  17. * 构造方法
  18. * @param string $question 问题
  19. * @param bool $default 默认答案
  20. * @param string $trueAnswerRegex 验证正则
  21. */
  22. public function __construct($question, $default = true, $trueAnswerRegex = '/^y/i')
  23. {
  24. parent::__construct($question, (bool) $default);
  25. $this->trueAnswerRegex = $trueAnswerRegex;
  26. $this->setNormalizer($this->getDefaultNormalizer());
  27. }
  28. /**
  29. * 获取默认的答案回调
  30. * @return callable
  31. */
  32. private function getDefaultNormalizer()
  33. {
  34. $default = $this->getDefault();
  35. $regex = $this->trueAnswerRegex;
  36. return function ($answer) use ($default, $regex) {
  37. if (is_bool($answer)) {
  38. return $answer;
  39. }
  40. $answerIsTrue = (bool) preg_match($regex, $answer);
  41. if (false === $default) {
  42. return $answer && $answerIsTrue;
  43. }
  44. return !$answer || $answerIsTrue;
  45. };
  46. }
  47. }