Cake\Console\ConsoleIo::askChoice PHP Method

askChoice() public method

Prompts the user for input based on a list of options, and returns it.
public askChoice ( string $prompt, string | array $options, string | null $default = null ) : mixed
$prompt string Prompt text.
$options string | array Array or string of options.
$default string | null Default input value.
return mixed Either the default value, or the user-provided input.
    public function askChoice($prompt, $options, $default = null)
    {
        if ($options && is_string($options)) {
            if (strpos($options, ',')) {
                $options = explode(',', $options);
            } elseif (strpos($options, '/')) {
                $options = explode('/', $options);
            } else {
                $options = [$options];
            }
        }
        $printOptions = '(' . implode('/', $options) . ')';
        $options = array_merge(array_map('strtolower', $options), array_map('strtoupper', $options), $options);
        $in = '';
        while ($in === '' || !in_array($in, $options)) {
            $in = $this->_getInput($prompt, $printOptions, $default);
        }
        return $in;
    }

Usage Example

Beispiel #1
0
 /**
  * Creates a file at given path
  *
  * @param string $path Where to put the file.
  * @param string $contents Content to put in the file.
  * @return bool Success
  * @link http://book.cakephp.org/3.0/en/console-and-shells.html#creating-files
  */
 public function createFile($path, $contents)
 {
     $path = str_replace(DS . DS, DS, $path);
     $this->_io->out();
     if (is_file($path) && empty($this->params['force']) && $this->interactive) {
         $this->_io->out(sprintf('<warning>File `%s` exists</warning>', $path));
         $key = $this->_io->askChoice('Do you want to overwrite?', ['y', 'n', 'a', 'q'], 'n');
         if (strtolower($key) === 'q') {
             $this->_io->out('<error>Quitting</error>.', 2);
             return $this->_stop();
         }
         if (strtolower($key) === 'a') {
             $this->params['force'] = true;
             $key = 'y';
         }
         if (strtolower($key) !== 'y') {
             $this->_io->out(sprintf('Skip `%s`', $path), 2);
             return false;
         }
     } else {
         $this->out(sprintf('Creating file %s', $path));
     }
     $File = new File($path, true);
     if ($File->exists() && $File->writable()) {
         $data = $File->prepare($contents);
         $File->write($data);
         $this->_io->out(sprintf('<success>Wrote</success> `%s`', $path));
         return true;
     }
     $this->_io->err(sprintf('<error>Could not write to `%s`</error>.', $path), 2);
     return false;
 }