From b464fe3cd79015156a942c366a9954f29ab6dd0e Mon Sep 17 00:00:00 2001 From: Andrey Kutejko Date: Tue, 17 Dec 2013 21:26:35 +0200 Subject: [PATCH] CLI helper class --- src/cli.php | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/cli.php diff --git a/src/cli.php b/src/cli.php new file mode 100644 index 0000000..ced4b0a --- /dev/null +++ b/src/cli.php @@ -0,0 +1,77 @@ + [parameter...]\n\n"; + echo "Available commands:\n\n"; + + $cmds = $this->commands(); + + $max_len = 0; + foreach ($cmds as $cmd) { + list($key, $method, $description) = $cmd; + $max_len = max($max_len, strlen($key)); + } + + $pad = floor(($max_len + 11) / 8) * 8; + foreach ($cmds as $cmd) { + list($key, $method, $description) = $cmd; + echo " ".str_pad($key, $pad).$description."\n"; + } + echo "\n"; + } + + public function execute() + { + $args = $this->getArgs(); + + if (count($args) <= 1) { + $this->printUsage($args[0]); + return 1; + } + + $command = $args[1]; + $command_args = array_slice($args, 2); + + foreach ($this->commands() as $cmd) { + list($key, $method, $description) = $cmd; + if ($key === $command) { + if (method_exists($this, $method)) { + return call_user_func_array(array($this, $method), $command_args); + } else { + echo "Method $method is not defined.\n"; + return 1; + } + } + } + + echo "Unknown command.\n"; + return 1; + } + + public static function run() + { + if (php_sapi_name() === 'cli') { + $cli = new static; + $code = $cli->execute(); + exit($code); + } + } +} + -- 2.49.0