Created
June 16, 2011 13:22
-
-
Save icio/1029215 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env php | |
<?php | |
route(); | |
/* | |
* ======================================================= | |
*/ | |
/** | |
* Route the user input to the correct function. | |
* | |
* CLI Commands are given in the form of: | |
* ./user-stats.php [fn] paramA paramB ... | |
* which are passed to a php function of the form | |
* function do_fn($paramA, $paramB, ...) {} | |
*/ | |
function route() | |
{ | |
global $argc, $argv; | |
if ($argc < 2) do_help(); | |
// Check the function exists | |
$fn = 'do_'.$argv[1]; | |
if (!function_exists($fn)) do_help(); | |
// Check we've got the required number of parameters | |
$ref = new ReflectionFunction($fn); | |
if ($argc-2 < $ref->getNumberOfRequiredParameters()) do_help($argv[1]); | |
// Call the function | |
$ref->invokeArgs(array_slice($argv, 2)); | |
} | |
/* | |
* ======================================================= | |
*/ | |
/** | |
* Outputs help information. | |
* | |
* @param string $fn (optional) A function to request specific help | |
* information on. | |
*/ | |
function do_help($fn = null) | |
{ | |
// Functions we're interested in | |
if (isset($fn) && function_exists('do_'.$fn)) { | |
$fns = array('do_'.$fn); | |
} else { | |
$fns = get_defined_functions(); | |
$fns = $fns['user']; | |
$fns = array_filter($fns, function($fn) { return substr($fn, 0, 3) == 'do_'; }); | |
} | |
// Print help for each function | |
echo 'Usage: ', basename(__FILE__), " [fn] [params]\nFunctions:\n"; | |
foreach ($fns as $fn) { | |
$ref = new ReflectionFunction($fn); | |
$paramSig = array(); | |
$params = $ref->getParameters(); | |
foreach ($params as $param) { | |
$paramSig[] = $param->getName() . ($param->isOptional() ? '='.var_export($param->getDefaultValue(),1) : ''); | |
} | |
$paramSig = implode(', ', $paramSig); | |
$help = "\t".str_replace("\n", "\n\t", $ref->getDocComment()); | |
echo ' - ', substr($fn, 3), '(', $paramSig, ')', ":\n", $help, "\n"; | |
} | |
exit; | |
} | |
/** | |
* A test function that outputs the first two arguments. | |
* | |
* @param string $a | |
* @param string $b (optional) | |
*/ | |
function do_test($a, $b='B') | |
{ | |
echo 'The first two of ', func_num_args(), ' arguments: ', $a, ', ', $b, "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment