/** * Initialize PLUG CLI environment * @todo research CGI environment, differences to cli * @return Void */ static function init() { switch (PHP_SAPI) { // Ideally we want to be runnning as CLI case 'cli': break; // Special conditions to ensure CGI runs as CLI // Special conditions to ensure CGI runs as CLI case 'cgi': // Ensure resource constants are defined if (!defined('STDERR')) { define('STDERR', fopen('php://stderr', 'w')); } if (!defined('STDOUT')) { define('STDOUT', fopen('php://stdout', 'w')); } break; default: echo "Command line only\n"; exit(1); } // Default error logger function PLUG::set_error_logger(array(__CLASS__, 'format_logline')); // parse command line arguments from argv global global $argv, $argc; // first cli arg is always current script. second arg will be script arg passed to shell wrapper for ($i = 1; $i < $argc; $i++) { $arg = $argv[$i]; // Each command line argument may take following forms: // 1. "Any single argument", no point parsing this unless it follows #2 below // 2. "-aBCD", one or more switches, parse into 'a'=>true, 'B'=>true, and so on // 3. "-a value", flag used with following value, parsed to 'a'=>'value' // 4. "--longoption", GNU style long option, parse into 'longoption'=>true // 5. "--longoption=value", as above, but parse into 'longoption'=>'value' // 6."any variable name = any value" $pair = explode('=', $arg, 2); if (isset($pair[1])) { $name = trim($pair[0]); if (strpos($name, '--') === 0) { // #5. trimming "--" from option, tough luck if you only used one "-" $name = trim($name, '-'); } // else is #6, any pair $name and self::$args[$name] = trim($pair[1]); } else { if (strpos($arg, '--') === 0) { // #4. long option, no value $name = trim($arg, "-\n\r\t "); $name and self::$args[$name] = true; } else { if ($arg && $arg[0] === '-') { $flags = preg_split('//', trim($arg, "-\n\r\t "), -1, PREG_SPLIT_NO_EMPTY); foreach ($flags as $flag) { self::$args[$flag] = true; } // leave $flag set incase a value follows. continue; } else { if (isset($flag)) { self::$args[$flag] = trim($arg); } } } } // dispose of last flag unset($flag); // next arg } }