diff --git "a/class-cli\\Input.php" "b/class-cli\\Input.php" new file mode 100644 index 0000000..51e8ec2 --- /dev/null +++ "b/class-cli\\Input.php" @@ -0,0 +1,64 @@ +. + +# Command line interface +namespace cli; + +class Input { + + /** + * Do a yes/no question + * + * @param $question string e.g. 'Do you want to continue?' + * @param $default string e.g. 'y' + * @return string e.g. 'y' + */ + public static function yesNoQuestion( $question, $default = 'y' ) { + return self::singleCharQuestion( $question, 'yn', $default ); + } + + /** + * Do a single character question + * + * @param $question string e.g. 'Do you want to continue?' + * @param $choices string e.g. 'yn' + * @param $default string e.g. 'y' + */ + public static function singleCharQuestion( $question, $choices, $default ) { + $choices = str_split( $choices ); + foreach( $choices as &$choice ) { + if( $choice === $default ) { + $choice = strtoupper( $choice ); + } + } + echo "$question [" . implode( '/', $choices ) . "]\n"; + return self::read( $default ); + } + + /** + * Ask for user standard input + * + * @param $default string Default string when empty input + * @return string + */ + public static function read( $default = '' ) { + $handle = fopen( 'php://stdin', 'r' ); + $line = rtrim( fgets( $handle ) ); + fclose( $handle ); + return '' === $line ? $default : $line; + } +}