mirror of
https://github.com/yiisoft/yii2.git
synced 2025-12-01 15:07:49 +08:00
more on console apps
This commit is contained in:
@@ -60,4 +60,56 @@ class Controller extends \yii\base\Controller
|
||||
\Yii::$application->end(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads input via the readline PHP extension if that's available, or fgets() if readline is not installed.
|
||||
*
|
||||
* @param string $message to echo out before waiting for user input
|
||||
* @param string $default the default string to be returned when user does not write anything.
|
||||
* Defaults to null, means that default string is disabled.
|
||||
* @return mixed line read as a string, or false if input has been closed
|
||||
*/
|
||||
public function prompt($message, $default = null)
|
||||
{
|
||||
if($default !== null) {
|
||||
$message .= " [$default] ";
|
||||
}
|
||||
else {
|
||||
$message .= ' ';
|
||||
}
|
||||
|
||||
if(extension_loaded('readline')) {
|
||||
$input = readline($message);
|
||||
if($input !== false) {
|
||||
readline_add_history($input);
|
||||
}
|
||||
}
|
||||
else {
|
||||
echo $message;
|
||||
$input = fgets(STDIN);
|
||||
}
|
||||
|
||||
if($input === false) {
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
$input = trim($input);
|
||||
return ($input === '' && $default !== null) ? $default : $input;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks user to confirm by typing y or n.
|
||||
*
|
||||
* @param string $message to echo out before waiting for user input
|
||||
* @param boolean $default this value is returned if no selection is made.
|
||||
* @return boolean whether user confirmed
|
||||
*/
|
||||
public function confirm($message, $default = false)
|
||||
{
|
||||
echo $message . ' (yes|no) [' . ($default ? 'yes' : 'no') . ']:';
|
||||
|
||||
$input = trim(fgets(STDIN));
|
||||
return empty($input) ? $default : !strncasecmp($input, 'y', 1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user