Kommandozeilen I/O Klasse
Command line i/o class
This is a simple wrapper class for getting arguments (more elaborated than getopt
) and
printing to stdout
and stderr
with colors.
Dies ist eine simple Wrapperklasse, um Kommanrozeilenargumente (besser als mit getopt
)
einzulesen, sowie auf stdout
und stderr
mit Farbigem Text auszugeben.
Sample source code
Anwendungsbeispiel
<?
require_once('swlib/swlib.class.php');
use sw\CommandLineInterface as cli;
// Parses the command line arguments and detects parameters.
// You can specify boolean options (e.g. --help, -h, --verbose) that evaluate
// to TRUE if they appear in the arument list.
//
// Returns an array containing the key-value paramters and positional
// arguments.
//
// Parameters are detected allowing the following formats:
//
// --<KEY>=<VALUE>
// --<KEY>= <VALUE>
// --<KEY> = <VALUE>
// -<KEY> <VALUE>
// -<SINGLE CHARACTER BOOLEAN OPTION>
// --<BOOLEAN OPTION>
// -<OPT1><OPT2><OPT3><KEY> <VALUE>
// -<OPT> [other options] -- <ARGUMENTS HERE ARE INTERPRETED POSITIONAL>
//
// Examples:
//
// ./myscript -vczf 'file name' (e.g. like tar command)
// ./myscript -v -c -z -f 'file'
// ./myscript --verbose -c -z --file='file'
// ./myscript -abc --key= value -- only positional arguments follow
// Here we use -h, -v, --help, --verbose as boolean options
$args = cli::getargs(array('h', 'v', 'help', 'verbose'));
// The text representation of the returned array
$args_text = print_r($args, true) . "\n";
// We colorise this is to demonstrate the class color constants:
$replace = array(
"|( \[.*?\] )|smix" => cli::COLOR_FG_RED . "$1" . cli::COLOR_NO,
"|( Array\s*\( )|smix" => cli::COLOR_FG_BLUE . "$1" . cli::COLOR_NO,
"|( \) )|smix" => cli::COLOR_FG_BLUE . "$1" . cli::COLOR_NO,
"|( => )|smix" => cli::COLOR_FG_GREEN . "$1" . cli::COLOR_NO,
);
$args_text = preg_replace(array_keys($replace), $replace, $args_text);
// And we print it to stderr
cli::stderr("\n" . $args_text . "\n\n");
Output
Ausgabe
$php cli.test.php -v --verbose --key1=value1 -key2 value2 -- DASH -NOT --INTERPRETED HERE
Array
(
[0] => cli.test.php
[v] => 1
[verbose] => 1
[key1] => value1
[k] => 1
[e] => 1
[y] => 1
[2] => value2
[3] => DASH
[4] => -NOT
[5] => --INTERPRETED
[6] => HERE
)
Class source code
Klassen-Quelltext
<?php
/**
* Command line interface related functions
* @gpackage de.atwillys.sw.php.swLib
* @author Stefan Wilhelm
* @copyright Stefan Wilhelm, 2007-2012
* @license GPL2
* @version 1.0
*/
namespace sw;
class CommandLineInterface {
/**
* Color codes
*/
const COLOR_NO = "\033[0m";
const COLOR_DEFAULT = "\033[0m";
const COLOR_NORMAL = "\033[0m";
const COLOR_FG_BLACK = "\033[0;30m";
const COLOR_FG_DARK_GRAY = "\033[1;30m";
const COLOR_FG_BLUE = "\033[0;34m";
const COLOR_FG_LIGHT_BLUE = "\033[1;34m";
const COLOR_FG_GREEN = "\033[0;32m";
const COLOR_FG_LIGHT_GREEN = "\033[1;32m";
const COLOR_FG_CYAN = "\033[0;36m";
const COLOR_FG_LIGHT_CYAN = "\033[1;36m";
const COLOR_FG_RED = "\033[0;31m";
const COLOR_FG_LIGHT_RED = "\033[1;31m";
const COLOR_FG_PURPLE = "\033[0;35m";
const COLOR_FG_LIGHT_PURPLE = "\033[1;35m";
const COLOR_FG_BROWN = "\033[0;33m";
const COLOR_FG_YELLOW = "\033[1;33m";
const COLOR_FG_LIGHT_GRAY = "\033[0;37m";
const COLOR_FG_WHITE = "\033[1;37m";
const COLOR_BG_BLACK = "\033[40m";
const COLOR_BG_RED = "\033[41m";
const COLOR_BG_GREEN = "\033[42m";
const COLOR_BG_YELLOW = "\033[43m";
const COLOR_BG_BLUE = "\033[44m";
const COLOR_BG_MAGENTA = "\033[45m";
const COLOR_BG_CYAN = "\033[46m";
const COLOR_BG_LIGHT_GRAY = "\033[47m";
/**
* @function getargs
*
* Program argument parsing. $flag_params describes flag options without values.
* Returns empty array on error.
*
* Test code: print_r(getargs(array('a','b','alpha')));
*
* Test command: ./getargs -xvzf 'last character is value option' \
* -xya 'a is bool, so this is a positional argument'\
* --alpha 'alpha is bool, this is positional as well'\
* --value1='text-value' --value2 'no "=" notation'\
* --\
* '+++ only positional follow after "--" +++'\
* --help\
* -abc
*
* @author stfwi
* @license GPL2
* @param array $bool_opts = array()
* @return array
* @throws -
*/
public static function getargs($bool_opts = array()) {
if (!isset($GLOBALS['argv']) || empty($GLOBALS['argv'])) {
return array();
}
$args = $GLOBALS['argv'];
$return = array();
reset($args);
while (list($k, $arg) = each($args)) {
if (strlen($arg) == 0) {
// argument is empty string '', as positional argument
$return[] = $arg;
} else if ($arg == '--') {
// End of options, only operands follow (positional arguments)
while (list($k, $arg) = each($args)) {
$return[] = $arg;
}
return $return;
} else if (strpos($arg, '--') === 0) {
$arg = ltrim($arg, '-');
if (in_array($arg, $bool_opts)) {
$return[$arg] = true;
} else if (strpos($arg, '=') !== false) {
// Covers --arg=something, '--arg = something' and --arg=
$arg = explode('=', $arg, 2);
$return[trim($arg[0])] = trim($arg[1]);
} else {
// Problematic, could be --name '-=[MEEEEE]=-', or --verbose -k, we assume
// the first as --verbose should be otherwise defined in $bool_opts.
if (current($args) !== false) {
// There is another arg after this one --> value
list($k, $v) = each($args);
$return[$arg] = $v;
} else {
// Then a unspecified bool option? Preferred
$return[$arg] = '';
}
}
} else if ($arg == '-') {
// This is an error as positional argument (if no value of another argument)
$return[] = $arg;
} else if (strpos($arg, '-') === 0) {
// "-" args can have only one character, can have a value following but
// no "=", like "-k=1". In short notation, the last character can denote
// a value arg.
$arg = str_split(trim($arg, '- '));
$last = array_pop($arg);
// The first are all bool
foreach ($arg as $v) {
$return[$v] = true;
}
// The last has to be checked for bool, otherwise value arg
if (in_array($last, $bool_opts)) {
$return[$last] = true;
} else if (current($args) !== false) {
list($k, $v) = each($args);
$return[$last] = $v;
} else {
$return[$last] = true;
}
} else {
$return[] = $arg;
}
}
return $return;
}
/**
* Prints to STDOUT
* @param string $text
* @return void
*/
public static function stdout($text) {
print(@strval($text));
}
/**
* Prints to STDERR
* @param string $text
* @return void
*/
public static function stderr($text) {
@file_put_contents('php://stderr', self::COLOR_FG_RED . "$text" . self::COLOR_NO, FILE_APPEND);
}
}