示例#1
0
 /**
  * Prompts the user for input and validates it.
  *
  * @param string $text    prompt string
  * @param array  $options the options to validate the input:
  *
  * - `required`: whether it is required or not
  * - `default`: default value if no input is inserted by the user
  * - `pattern`: regular expression pattern to validate user input
  * - `validator`: a callable function to validate input. The function must accept two parameters:
  * - `input`: the user input to validate
  * - `error`: the error value passed by reference if validation failed
  *
  * @return string the user input
  */
 public static function prompt($text, $options = [])
 {
     $options = ArrayHelper::merge(['required' => false, 'default' => null, 'pattern' => null, 'validator' => null, 'error' => 'Invalid input.'], $options);
     $error = null;
     top:
     $input = $options['default'] ? static::input("{$text} [" . $options['default'] . '] ') : static::input("{$text} ");
     if ($input === '') {
         if (isset($options['default'])) {
             $input = $options['default'];
         } elseif ($options['required']) {
             static::output($options['error']);
             goto top;
         }
     } elseif ($options['pattern'] && !preg_match($options['pattern'], $input)) {
         static::output($options['error']);
         goto top;
     } elseif ($options['validator'] && !call_user_func_array($options['validator'], [$input, &$error])) {
         static::output(isset($error) ? $error : $options['error']);
         goto top;
     }
     return $input;
 }