Ejemplo n.º 1
0
 /**
  * Same as \cli\prompt except that it allows empty input
  * @param string $question
  * @param bool $default
  * @param string $marker
  * @return string
  */
 public static function promptAllowingEmpty($question, $default = false, $marker = ': ')
 {
     if ($default && strpos($question, '[') === false) {
         $question .= ' [' . $default . ']';
     }
     while (true) {
         \cli\Streams::out($question . $marker);
         $line = \cli\Streams::input();
         return $line;
     }
 }
Ejemplo n.º 2
0
 /**
  * Displays an array of strings as a menu where a user can enter a number to
  * choose an option. The array must be a single dimension with either strings
  * or objects with a `__toString()` method.
  *
  * @param array   $items    The list of items the user can choose from.
  * @param string  $default  The index of the default item.
  * @param string  $title    The message displayed to the user when prompted.
  * @return string  The index of the chosen item.
  * @see cli\line()
  * @see cli\input()
  * @see cli\err()
  */
 public static function menu($items, $default = false, $title = 'Choose an item')
 {
     $map = array_values($items);
     if ($default && strpos($title, '[') === false && isset($items[$default])) {
         $title .= ' [' . $items[$default] . ']';
     }
     foreach ($map as $idx => $item) {
         \cli\Streams::line('  %d. %s', $idx + 1, (string) $item);
     }
     \cli\Streams::line();
     while (true) {
         fwrite(static::$out, sprintf('%s: ', $title));
         $line = \cli\Streams::input();
         if (is_numeric($line)) {
             $line--;
             if (isset($map[$line])) {
                 return array_search($map[$line], $items);
             }
             if ($line < 0 || $line >= count($map)) {
                 \cli\Streams::err('Invalid menu selection: out of range');
             }
         } else {
             if (isset($default)) {
                 return $default;
             }
         }
     }
 }
Ejemplo n.º 3
0
/**
 * Takes input from `STDIN` in the given format. If an end of transmission
 * character is sent (^D), an exception is thrown.
 *
 * @param string  $format  A valid input format. See `fscanf` for documentation.
 *                         If none is given, all input up to the first newline
 *                         is accepted.
 * @return string  The input with whitespace trimmed.
 * @throws \Exception  Thrown if ctrl-D (EOT) is sent as input.
 */
function input($format = null)
{
    return \cli\Streams::input($format);
}