本文整理汇总了PHP中Console_CommandLine::parse方法的典型用法代码示例。如果您正苦于以下问题:PHP Console_CommandLine::parse方法的具体用法?PHP Console_CommandLine::parse怎么用?PHP Console_CommandLine::parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Console_CommandLine
的用法示例。
在下文中一共展示了Console_CommandLine::parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: run
public function run()
{
$this->concentrator = new Concentrate_Concentrator();
$this->parser = Console_CommandLine::fromXmlFile($this->getUiXml());
try {
$result = $this->parser->parse();
$this->setOptions($result->options);
$this->setWebRoot($result->args['webroot']);
$this->loadDataFiles();
if ($this->combine) {
$this->writeCombinedFiles();
$this->writeCombinedFlagFile();
}
if ($this->compile) {
$this->writeCompiledFiles();
$this->writeCompiledFlagFile();
}
if ($this->minify) {
$this->writeMinifiedFiles();
$this->writeMinifiedFlagFile();
}
} catch (Console_CommandLine_Exception $e) {
$this->displayError($e->getMessage() . PHP_EOL);
} catch (Exception $e) {
$this->displayError($e->getMessage() . PHP_EOL, false);
$this->displayError($e->getTraceAsString() . PHP_EOL);
}
}
示例2: run
/**
* Process the request
*
* @param array $params Runner options
*
* @return void
*/
public function run($params = null)
{
$this->parser = new Parser($this->paths);
try {
$argc = $params === null ? null : count($params);
$this->result = $this->parser->parse($argc, $params);
} catch (\Exception $e) {
$this->parser->displayError($e->getMessage());
}
$this->parse();
}
示例3: run
/**
* Run tasks (basically, try to parse a command line)
*/
public function run() {
// Parse the command line arguments
try {
$this->cli = $this->parser->parse();
} catch (Exception $e) {
$this->parser->displayError($e->getMessage());
exit($e->getCode());
}
}
示例4: process
/**
* Process command
*
* @return string
*/
public function process()
{
try {
$this->command = $this->parser->parse();
if (empty($this->command->command_name)) {
$this->parser->displayUsage();
self::end(0);
}
$return = $this->controller->execute($this->command->command_name, $this->command->command->options, $this->command->command->args, $this->color, $this->logger, $this->tasks);
} catch (ShellException $se) {
$this->parser->displayError($this->color->convert("\n\n%R" . $se->getMessage() . "%n\n"));
self::end(1);
} catch (Exception $e) {
$this->parser->displayError($this->color->convert("\n\n%r" . $e->getMessage() . "%n\n"));
self::end(1);
}
echo "\n" . $return . "\n\n";
self::end(0);
}
示例5: array
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
*/
// Include the Console_CommandLine package.
require_once 'Console/CommandLine.php';
// create the parser
$parser = new Console_CommandLine(array('description' => 'zip given files using the php zip module.', 'version' => '1.0.0'));
// add an option to make the program verbose
$parser->addOption('verbose', array('short_name' => '-v', 'long_name' => '--verbose', 'action' => 'StoreTrue', 'description' => 'turn on verbose output'));
// add an option to delete original files after zipping
$parser->addOption('delete', array('short_name' => '-d', 'long_name' => '--delete', 'action' => 'StoreString', 'description' => 'delete original files after zip operation', 'choices' => array('foo', 'bar'), 'add_list_option' => true));
// add the files argument, the user can specify one or several files
$parser->addArgument('files', array('multiple' => true, 'description' => 'list of files to zip separated by spaces'));
// add the zip file name argument
$parser->addArgument('zipfile', array('description' => 'zip file name'));
// run the parser
try {
$result = $parser->parse();
// write your program here...
print_r($result->options);
print_r($result->args);
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
示例6: array
*/
// Load bootstrap for autoload and logger
set_include_path(".:" . get_include_path());
require_once "bootstrap.php";
// Instanciate export service
$service = new Alternc_Tools_Domains_Import(array("db" => $db));
// Instanciate command line parser
$consoleParser = new Console_CommandLine(array("description" => "Imports Alternc domains from a file for import and gets ready for sync."));
// Configure command line parser
$consoleParser->add_version_option = false;
$consoleParser->addOption("input_file", array("help_name" => "/tmp/out.json", "short_name" => "-i", "long_name" => "--input-file", "description" => "Input file name and path", 'default' => $service->default_input));
$consoleParser->addOption("restrict_input_file", array("help_name" => "/tmp/missing.txt", "short_name" => "-r", "long_name" => "--restrict-file", "description" => "Domain list, one per line. Others won't be imported.", 'default' => ""));
$consoleParser->addOption("force_uid", array("help_name" => "2001", "short_name" => "-u", "long_name" => "--force-uid", "description" => "Force the domain owner", 'default' => null));
// Run the command line parser
try {
$commandLineResult = $consoleParser->parse();
// Run the service
if (!($result = $service->import($commandLineResult))) {
throw new \Exception("Import process failed");
}
$message = "";
$level = Logger\AbstractLogger::INFO;
if (isset($result["message"])) {
$message .= $result["message"] . "\n";
}
if (isset($result["successList"]) && count($result["successList"])) {
$message .= "# Success\n";
$message .= implode("\n", $result["successList"]) . "\n";
}
if (isset($result["errorsList"]) && count($result["errorsList"])) {
$level = Logger\AbstractLogger::WARNING;
示例7: array
// Pull in the configuration file.. (Yes this actually works)
$config = (include __DIR__ . "/config.php");
// Set debugging if enabled
define('DEBUG', !empty($config->debug));
// Load up the class auto loader
require_once __DIR__ . "/../classes/Init.php";
include "common.php";
$parser = new Console_CommandLine();
$parser->description = "Convers the raw spell icons into strips for the trainer";
$parser->version = "0.0.1";
$parser->addOption('newsize', array('long_name' => '--size', 'description' => 'Size of new icons', 'default' => 64, 'help_name' => 'SIZE', 'action' => 'StoreInt'));
$parser->addOption('prefix', array('long_name' => '--prefix', 'description' => 'The output filename prefix', 'default' => 'trainer-icon-', 'help_name' => 'PREFIX'));
$parser->addArgument('mapfile', array('description' => 'The input JSON map file process', 'help_name' => 'INPUTFILE'));
$parser->addArgument('outputdir', array('description' => 'The output dir for images', 'help_name' => 'OUTPUTDIR'));
try {
$args = $parser->parse();
} catch (Exception $ex) {
$parser->displayError($ex->getMessage());
}
$map = json_decode(file_get_contents($args->args['mapfile']));
$size = $args->options['newsize'];
$imagedir = dirname($args->args['mapfile']);
$imageunused = $imagedir . DIRECTORY_SEPARATOR . 'unused';
if (!is_dir($imageunused)) {
mkdir($imageunused);
}
$d = dir($imageunused);
while (false !== ($entry = $d->read())) {
if ($entry[0] == '.') {
continue;
}
示例8: __invoke
/**
* Runs this pinentry
*
* @return void
*/
public function __invoke()
{
$this->parser = $this->getCommandLineParser();
try {
$result = $this->parser->parse();
$this->setVerbosity($result->options['verbose']);
$this->setLogFilename($result->options['log']);
$this->connect();
$this->initPinsFromENV();
while (($line = fgets($this->stdin, self::CHUNK_SIZE)) !== false) {
$this->parseCommand(mb_substr($line, 0, -1, '8bit'));
if ($this->moribund) {
break;
}
}
$this->disconnect();
} catch (Console_CommandLineException $e) {
$this->log($e->getMessage() . PHP_EOL, slf::VERBOSITY_ERRORS);
exit(1);
} catch (Exception $e) {
$this->log($e->getMessage() . PHP_EOL, self::VERBOSITY_ERRORS);
$this->log($e->getTraceAsString() . PHP_EOL, self::VERBOSITY_ERRORS);
exit(1);
}
}
示例9: run
/**
* Entry-point for Erebot.
*
* \return
* This method never returns.
* Instead, the program exits with an appropriate
* return code when Erebot is stopped.
*/
public static function run()
{
// Apply patches.
\Erebot\Patches::patch();
// Load the configuration for the Dependency Injection Container.
$dic = new \Symfony\Component\DependencyInjection\ContainerBuilder();
$dic->setParameter('Erebot.src_dir', __DIR__);
$loader = new \Symfony\Component\DependencyInjection\Loader\XmlFileLoader($dic, new \Symfony\Component\Config\FileLocator(getcwd()));
$dicConfig = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'defaults.xml';
$dicCwdConfig = getcwd() . DIRECTORY_SEPARATOR . 'defaults.xml';
if (!strncasecmp(__FILE__, 'phar://', 7)) {
if (!file_exists($dicCwdConfig)) {
copy($dicConfig, $dicCwdConfig);
}
$dicConfig = $dicCwdConfig;
} elseif (file_exists($dicCwdConfig)) {
$dicConfig = $dicCwdConfig;
}
$loader->load($dicConfig);
// Determine availability of PHP extensions
// needed by some of the command-line options.
$hasPosix = in_array('posix', get_loaded_extensions());
$hasPcntl = in_array('pcntl', get_loaded_extensions());
$logger = $dic->get('logging');
$localeGetter = $dic->getParameter('i18n.default_getter');
$coreTranslatorCls = $dic->getParameter('core.classes.i18n');
$translator = new $coreTranslatorCls("Erebot\\Core");
$categories = array('LC_MESSAGES', 'LC_MONETARY', 'LC_TIME', 'LC_NUMERIC');
foreach ($categories as $category) {
$locales = call_user_func($localeGetter);
$locales = empty($locales) ? array() : array($locales);
$localeSources = array('LANGUAGE' => true, 'LC_ALL' => false, $category => false, 'LANG' => false);
foreach ($localeSources as $source => $multiple) {
if (!isset($_SERVER[$source])) {
continue;
}
if ($multiple) {
$locales = explode(':', $_SERVER[$source]);
} else {
$locales = array($_SERVER[$source]);
}
break;
}
$translator->setLocale($translator->nameToCategory($category), $locales);
}
// Also, include some information about the version
// of currently loaded PHAR modules, if any.
$version = 'dev-master';
if (!strncmp(__FILE__, 'phar://', 7)) {
$phar = new \Phar(\Phar::running(true));
$md = $phar->getMetadata();
$version = $md['version'];
}
if (defined('Erebot_PHARS')) {
$phars = unserialize(Erebot_PHARS);
ksort($phars);
foreach ($phars as $module => $metadata) {
if (strncasecmp($module, 'Erebot_Module_', 14)) {
continue;
}
$version .= "\n with {$module} version {$metadata['version']}";
}
}
\Console_CommandLine::registerAction('StoreProxy', '\\Erebot\\Console\\StoreProxyAction');
$parser = new \Console_CommandLine(array('name' => 'Erebot', 'description' => $translator->gettext('A modular IRC bot written in PHP'), 'version' => $version, 'add_help_option' => true, 'add_version_option' => true, 'force_posix' => false));
$parser->accept(new \Erebot\Console\MessageProvider());
$parser->renderer->options_on_different_lines = true;
$defaultConfigFile = getcwd() . DIRECTORY_SEPARATOR . 'Erebot.xml';
$parser->addOption('config', array('short_name' => '-c', 'long_name' => '--config', 'description' => $translator->gettext('Path to the configuration file to use instead ' . 'of "Erebot.xml", relative to the current ' . 'directory.'), 'help_name' => 'FILE', 'action' => 'StoreString', 'default' => $defaultConfigFile));
$parser->addOption('daemon', array('short_name' => '-d', 'long_name' => '--daemon', 'description' => $translator->gettext('Run the bot in the background (daemon).' . ' [requires the POSIX and pcntl extensions]'), 'action' => 'StoreTrue'));
$noDaemon = new \Erebot\Console\ParallelOption('no_daemon', array('short_name' => '-n', 'long_name' => '--no-daemon', 'description' => $translator->gettext('Do not run the bot in the background. ' . 'This is the default, unless the -d option ' . 'is used or the bot is configured otherwise.'), 'action' => 'StoreProxy', 'action_params' => array('option' => 'daemon')));
$parser->addOption($noDaemon);
$parser->addOption('pidfile', array('short_name' => '-p', 'long_name' => '--pidfile', 'description' => $translator->gettext("Store the bot's PID in this file."), 'help_name' => 'FILE', 'action' => 'StoreString', 'default' => null));
$parser->addOption('group', array('short_name' => '-g', 'long_name' => '--group', 'description' => $translator->gettext('Set group identity to this GID/group during ' . 'startup. The default is to NOT change group ' . 'identity, unless configured otherwise.' . ' [requires the POSIX extension]'), 'help_name' => 'GROUP/GID', 'action' => 'StoreString', 'default' => null));
$parser->addOption('user', array('short_name' => '-u', 'long_name' => '--user', 'description' => $translator->gettext('Set user identity to this UID/username during ' . 'startup. The default is to NOT change user ' . 'identity, unless configured otherwise.' . ' [requires the POSIX extension]'), 'help_name' => 'USER/UID', 'action' => 'StoreString', 'default' => null));
try {
$parsed = $parser->parse();
} catch (\Exception $exc) {
$parser->displayError($exc->getMessage());
exit(1);
}
// Parse the configuration file.
$config = new \Erebot\Config\Main($parsed->options['config'], \Erebot\Config\Main::LOAD_FROM_FILE, $translator);
$coreCls = $dic->getParameter('core.classes.core');
$bot = new $coreCls($config, $translator);
$dic->set('bot', $bot);
// Use values from the XML configuration file
// if there is no override from the command line.
$overrides = array('daemon' => 'mustDaemonize', 'group' => 'getGroupIdentity', 'user' => 'getUserIdentity', 'pidfile' => 'getPidfile');
foreach ($overrides as $option => $func) {
if ($parsed->options[$option] === null) {
$parsed->options[$option] = $config->{$func}();
//.........这里部分代码省略.........
示例10: print_log
function print_log($message, $priority = PEAR_LOG_INFO)
{
global $logger;
$logger->log($message, $priority);
}
// Start parsing options
$parser = new Console_CommandLine();
$parser->description = 'Lists files in the current directory and creates a full size PDF or HTML page listing them with any available metadata.';
$parser->version = '1.1';
$parser->addArgument('url', array('multiple' => true, 'required' => TRUE));
$parser->addOption('quiet', array('short_name' => '-q', 'long_name' => '--quiet', 'description' => "Don't print status messages to stdout", 'action' => 'StoreTrue'));
$parser->addOption('verbose', array('short_name' => '-v', 'long_name' => '--verbose', 'description' => "Display extra log messages", 'action' => 'StoreTrue'));
$parser->addOption('rename', array('short_name' => '-r', 'long_name' => '--rename', 'description' => "Rename downloaded files to an autogenerated style.", 'action' => 'StoreTrue'));
global $commandline_input;
try {
$commandline_input = $parser->parse();
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
$options = $commandline_input->options;
if ($options['verbose']) {
$logger->setMask(PEAR_LOG_ALL);
}
if ($options['quiet']) {
$logger->setMask(PEAR_LOG_NONE);
}
if ($options['rename']) {
$rename_files = TRUE;
}
$urls = $commandline_input->args['url'];
#print_r($commandline_input);
示例11: parseOptions
protected function parseOptions()
{
$argf = new ARGF();
$argc =& $argf->argc();
$argv =& $argf->argv();
$optparser = new Console_CommandLine(array('name' => basename($argv[0]), 'description' => 'A php migratory tool from 4 to 5 written in pure php', 'version' => '0.0.1'));
$optparser->addOption('format', array('choices' => array('nodes', 'string', 'terminals', 'tokens', 'tree'), 'default' => 'string', 'description' => 'format of output (default: string)', 'long_name' => '--format', 'short_name' => '-f'));
$optparser->addOption('in_place', array('action' => 'StoreTrue', 'description' => 'edit files in place', 'long_name' => '--in-place', 'short_name' => '-i'));
$optparser->addOption('recursive', array('action' => 'StoreTrue', 'description' => 'migrate recursively', 'long_name' => '--recursive', 'short_name' => '-r'));
$optparser->addOption('suffixes', array('default' => 'php,php4,php5,inc', 'description' => 'suffixes of files to be migrated (default: php,php4,php5,inc)', 'long_name' => '--suffixes', 'short_name' => '-s'));
$optparser->addArgument('files', array('multiple' => true));
try {
$result = $optparser->parse();
} catch (Exception $e) {
$optparser->displayError($e->getMessage());
}
$options =& $result->options;
$args =& $result->args['files'];
if ($options['recursive']) {
if (count($args) < 2) {
$optparser->displayError('target directory must be specified with -r');
}
$target = $args[count($args) - 1];
if (!is_dir($target) && file_exists($target)) {
$optparser->displayError('target directory cannot be a regular file');
}
}
$options['suffixes'] = split(',', $options['suffixes']);
return array('options' => $options, 'args' => $args);
}
示例12: runUnsafe
/**
* Runs Chef given some command-line arguments.
*/
public function runUnsafe($userArgc = null, $userArgv = null)
{
// Get the arguments.
if ($userArgc == null || $userArgv == null) {
$getopt = new \Console_Getopt();
$userArgv = $getopt->readPHPArgv();
// `readPHPArgv` returns a `PEAR_Error` (or something like it) if
// it can't figure out the CLI arguments.
if (!is_array($userArgv)) {
throw new PieCrustException($userArgv->getMessage());
}
$userArgc = count($userArgv);
}
// Find whether the '--root' parameter was given.
$rootDir = null;
foreach ($userArgv as $arg) {
if (substr($arg, 0, strlen('--root=')) == '--root=') {
$rootDir = substr($arg, strlen('--root='));
break;
}
}
if ($rootDir == null) {
// No root given. Find it ourselves.
$rootDir = PathHelper::getAppRootDir(getcwd());
} else {
// The root was given.
$rootDir = PathHelper::getAbsolutePath($rootDir);
if (!is_dir($rootDir)) {
throw new PieCrustException("The given root directory doesn't exist: " . $rootDir);
}
}
// Build the appropriate app.
if ($rootDir == null) {
$pieCrust = new NullPieCrust();
} else {
$pieCrust = new PieCrust(array('root' => $rootDir, 'cache' => !in_array('--no-cache', $userArgv)));
}
// Set up the command line parser.
$parser = new \Console_CommandLine(array('name' => 'chef', 'description' => 'The PieCrust chef manages your website.', 'version' => PieCrustDefaults::VERSION));
// Sort commands by name.
$sortedCommands = $pieCrust->getPluginLoader()->getCommands();
usort($sortedCommands, function ($c1, $c2) {
return strcmp($c1->getName(), $c2->getName());
});
// Add commands to the parser.
foreach ($sortedCommands as $command) {
$commandParser = $parser->addCommand($command->getName());
$command->setupParser($commandParser, $pieCrust);
$this->addCommonOptionsAndArguments($commandParser);
}
// Parse the command line.
try {
$result = $parser->parse($userArgc, $userArgv);
} catch (Exception $e) {
$parser->displayError($e->getMessage());
return 1;
}
// If no command was given, use `help`.
if (empty($result->command_name)) {
$result = $parser->parse(2, array('chef', 'help'));
}
// Create the log.
$debugMode = $result->command->options['debug'];
$quietMode = $result->command->options['quiet'];
if ($debugMode && $quietMode) {
$parser->displayError("You can't specify both --debug and --quiet.");
return 1;
}
$log = \Log::singleton('console', 'Chef', '', array('lineFormat' => '%{message}'));
// Make the log available for debugging purposes.
$GLOBALS['__CHEF_LOG'] = $log;
// Handle deprecated stuff.
if ($result->command->options['no_cache_old']) {
$log->warning("The `--nocache` option has been renamed `--no-cache`.");
$result->command->options['no_cache'] = true;
}
// Run the command.
foreach ($pieCrust->getPluginLoader()->getCommands() as $command) {
if ($command->getName() == $result->command_name) {
try {
if ($rootDir == null && $command->requiresWebsite()) {
$cwd = getcwd();
throw new PieCrustException("No PieCrust website in '{$cwd}' ('_content/config.yml' not found!).");
}
$context = new ChefContext($pieCrust, $result, $log);
$context->setVerbosity($debugMode ? 'debug' : ($quietMode ? 'quiet' : 'default'));
$command->run($context);
return;
} catch (Exception $e) {
$log->emerg(self::getErrorMessage($e, $debugMode));
return 1;
}
}
}
}
示例13: check
function check($args)
{
global $argv;
// Command line parser
$parser = new Console_CommandLine(array('name' => $argv[0] . ' ' . $argv[1], 'description' => 'Check disk usage', 'version' => '0.0.1'));
$parser->addOption('rrd_file', array('short_name' => '-f', 'description' => 'RRD file', 'action' => 'StoreString'));
// $parser->addOption('datasource', array(
// 'short_name' => '-d',
// // 'long_name' => '--datasource',
// 'description' => 'Disk available RRD datasource',
// 'action' => 'StoreString'
// ));
// $parser->addOption('datasource', array(
// 'short_name' => '-u',
// // 'long_name' => '--datasource',
// 'description' => 'Disk used RRD datasource',
// 'action' => 'StoreString'
// ));
$parser->addOption('warning', array('short_name' => '-w', 'description' => 'Warning value (%, integer value, default: 20)', 'action' => 'StoreFloat', 'default' => 20));
$parser->addOption('critical', array('short_name' => '-c', 'description' => 'Critical value (%, integer value, default: 10)', 'action' => 'StoreFloat', 'default' => 10));
try {
$result = $parser->parse(count($args), $args);
$rrd_file = $result->options['rrd_file'];
if (empty($rrd_file)) {
echo 'No rrd_file specified' . "\n";
return NAGIOS_UNKNOWN;
}
if (!file_exists($rrd_file)) {
echo 'File ' . $rrd_file . ' doesn\'t seem to exist' . "\n";
return NAGIOS_UNKNOWN;
}
$v = new RRDValue($rrd_file);
// $datasource = $result->options['datasource'];
// if (empty($datasource)) {
// echo 'No datasource specified'."\n";
// echo 'Available datasources: '.implode(', ', $v->getDatasources())."\n";
// return NAGIOS_UNKNOWN;
// }
$disk_available_datasource = 'DISKFREE_available';
$disk_used_datasource = 'DISKFREE_used';
$disk_available_value = $v->get($disk_available_datasource);
$disk_used_value = $v->get($disk_used_datasource);
if (is_nan($disk_available_value)) {
echo 'Can\'t read disk available RRD value' . "\n";
return NAGIOS_UNKNOWN;
}
if (is_nan($disk_used_value)) {
echo 'Can\'t read disk free RRD value' . "\n";
return NAGIOS_UNKNOWN;
}
$percentage_available = $disk_available_value / ($disk_available_value + $disk_used_value);
$percentage_available = round($percentage_available * 100);
$disk_available_value_mb = round($disk_available_value / 1024 / 1024 / 1024, 1);
if ($percentage_available < $result->options['critical']) {
echo "DISK CRITICAL - free space: {$disk_available_value_mb} GB ({$percentage_available}%)";
return NAGIOS_CRITICAL;
} else {
if ($percentage_available < $result->options['warning']) {
echo "DISK WARNING - free space: {$disk_available_value_mb} GB ({$percentage_available}%)";
return NAGIOS_WARNING;
} else {
echo "DISK OK - free space: {$disk_available_value_mb} GB ({$percentage_available}%)";
return NAGIOS_OK;
}
}
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
return NAGIOS_UNKNOWN;
}
}
示例14: parseOptions
protected function parseOptions()
{
$argf = new ARGF();
$argc =& $argf->argc();
$argv =& $argf->argv();
$optparser = new Console_CommandLine(array('name' => basename($argv[0]), 'description' => 'Find bugs in PHP5 Programs', 'version' => '0.0.1'));
$optparser->addOption('format', array('long_name' => '--format', 'help_name' => 'FORMAT', 'choices' => array('nodes', 'string', 'terminals', 'tokens', 'tree'), 'default' => 'string', 'description' => 'format of output (default: string)'));
$optparser->addOption('suffixes', array('long_name' => '--suffixes', 'help_name' => 'PATTERNS', 'default' => 'php,yml', 'description' => 'suffixes of files to be checked (default: php,yml)'));
$optparser->addOption('priority', array('long_name' => '--priority', 'help_name' => 'LEVEL', 'choices' => array('low', 'middle', 'high'), 'default' => 'middle', 'description' => 'specify priority for bug reporting (default: middle)'));
$optparser->addOption('recursive', array('action' => 'StoreTrue', 'description' => 'check recursively', 'long_name' => '--recursive', 'short_name' => '-r'));
$optparser->addOption('debug', array('action' => 'StoreTrue', 'description' => 'turn on debug mode', 'long_name' => '--debug'));
$optparser->addArgument('files', array('multiple' => true));
try {
$result = $optparser->parse();
} catch (Exception $e) {
$optparser->displayError($e->getMessage());
}
$options =& $result->options;
$args =& $result->args['files'];
if ($options['recursive']) {
if (count($args) < 2) {
$optparser->displayError('target directory must be specified with -r');
}
$target = $args[count($args) - 1];
if (!is_dir($target) && file_exists($target)) {
$optparser->displayError('target directory cannot be a regular file');
}
}
$options['suffixes'] = split(',', $options['suffixes']);
return array('options' => $options, 'args' => $args);
}
示例15: array
<?php
// Load vendor lib paths from Composer
require_once 'vendor/autoload.php';
// Actual required libs
require_once 'Console/CommandLine.php';
$cmdline_parser = new Console_CommandLine();
$cmdline_parser->addArgument('inputFile', array('description' => 'Clover XML file'));
$cmdline_parser->addArgument('minPercentage', array('description' => 'Minimum percentage required to pass'));
$cmdline_parser->addOption('print_uncovered', array('short_name' => '-u', 'long_name' => '--uncovered', 'description' => 'Output uncovered lines', 'action' => 'StoreTrue'));
$cmdline_parser->addOption('print_uncovered_verbose', array('short_name' => '-v', 'long_name' => '--uncovered-verbose', 'description' => 'Output uncovered lines - more verbosely', 'action' => 'StoreTrue'));
$cmdline_parser->addOption('print_uncovered_verbose_whitespace', array('short_name' => '-w', 'long_name' => '--uncovered-verbose-whitespace', 'description' => 'Output uncovered lines - even if they contain only whitespace', 'action' => 'StoreTrue'));
$cmdline_result = $cmdline_parser->parse();
$inputFile = $cmdline_result->args['inputFile'];
$percentage = min(100, max(0, (int) $cmdline_result->args['minPercentage']));
if (!file_exists($inputFile)) {
throw new InvalidArgumentException('Invalid input file provided');
}
if (!$percentage) {
throw new InvalidArgumentException('An integer checked percentage must be given as second parameter');
}
$xml = new SimpleXMLElement(file_get_contents($inputFile));
$metrics = $xml->xpath('//metrics');
$totalElements = 0;
$checkedElements = 0;
foreach ($metrics as $metric) {
$totalElements += (int) $metric['elements'];
$checkedElements += (int) $metric['coveredelements'];
}
$coverage = $checkedElements / $totalElements * 100;
$exit_code = 0;