PageRenderTime 49ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/cli.php

https://bitbucket.org/etopian/php5-cli-framework
PHP | 352 lines | 210 code | 52 blank | 90 comment | 44 complexity | 4d702a9f52d2a355def10fe94893f68b MD5 | raw file
  1. <?
  2. /**
  3. * Command line interface
  4. * License: GPL v3
  5. * Allows easily writing OOP CLI scripts in PHP
  6. * @author sami
  7. *
  8. */
  9. class CLI{
  10. private $appname = 'CLI Framework';
  11. private $author = 'Sami Khan';
  12. private $copyright = '(c) 2011 Sami Khan';
  13. function __construct($appname = null, $author = null, $copyright = null) {
  14. if($appname){
  15. $this->appname = $appname;
  16. }
  17. if($author){
  18. $this->author = $author;
  19. }
  20. if($copyright){
  21. $this->copyright = $copyright;
  22. }
  23. if($this::isCli()){
  24. $args = $this::parseArgs();
  25. foreach($args['flags'] as $flag){
  26. $method_name = 'flag_'.$flag;
  27. if(method_exists($this, $method_name)){
  28. call_user_func(array($this, $method_name));
  29. //
  30. }
  31. }
  32. foreach($args['arguments'] as $arg){
  33. $method_name = 'argument_'.$arg;
  34. if(method_exists($this, $method_name)){
  35. call_user_func(array($this, $method_name));
  36. }
  37. }
  38. foreach($args['options'] as $arg){
  39. if(is_string($arg) === false && isset($arg[0]) && isset($arg[1])){
  40. $method_name = 'option_'.$arg[0];
  41. if(method_exists($this, $method_name)){
  42. call_user_func(array($this, $method_name), $arg[1]);
  43. }
  44. }else{
  45. $method_name = 'option_'.$arg;
  46. if(method_exists($this, $method_name)){
  47. call_user_func(array($this, $method_name));
  48. }
  49. }
  50. }
  51. global $argv;
  52. if(count($argv) === 1){
  53. $this->help();
  54. }else{
  55. $this->main();
  56. }
  57. exit();
  58. }
  59. }
  60. /**
  61. * Set the name of the app
  62. */
  63. public function setAppName(){
  64. }
  65. /**
  66. * Simply test whether or not we are running in CLI mode.
  67. */
  68. public static function isCli(){
  69. if(!defined('STDIN') && self::isCgi()) {
  70. if(getenv('TERM')) {
  71. return true;
  72. }
  73. return false;
  74. }
  75. return defined('STDIN');
  76. }
  77. public function getInput($question = "Are you sure you want to do this? Type 'yes' to continue:"){
  78. echo $question." ";
  79. $handle = fopen ("php://stdin","r");
  80. $line = fgets($handle);
  81. $answer = trim($line);
  82. return $answer;
  83. }
  84. /**
  85. "Input":
  86. ./script.php -a arg1 --opt1 arg2 -bcde --opt2=val2 arg3 arg4 arg5 -fg --opt3
  87. "print_r Output":
  88. Array
  89. (
  90. [exec] => ./script.php
  91. [options] => Array
  92. (
  93. [0] => opt1
  94. [1] => Array
  95. (
  96. [0] => opt2
  97. [1] => val2
  98. )
  99. [2] => opt3
  100. )
  101. [flags] => Array
  102. (
  103. [0] => a
  104. [1] => b
  105. [2] => c
  106. [3] => d
  107. [4] => e
  108. [5] => f
  109. [6] => g
  110. )
  111. [arguments] => Array
  112. (
  113. [0] => arg1
  114. [1] => arg2
  115. [2] => arg3
  116. [3] => arg4
  117. [4] => arg5
  118. )
  119. )
  120. *
  121. */
  122. public static function parseArgs($args = null) {
  123. if($args == null){
  124. global $argv,$argc;
  125. $args = $argv;
  126. }
  127. $ret = array(
  128. 'exec' => '',
  129. 'options' => array(),
  130. 'flags' => array(),
  131. 'arguments' => array(),
  132. );
  133. if(count($args) == 0){
  134. return $ret;
  135. }
  136. $ret['exec'] = array_shift( $args );
  137. while (($arg = array_shift($args)) != NULL) {
  138. // Is it a option? (prefixed with --)
  139. if ( substr($arg, 0, 2) === '--' ) {
  140. $option = substr($arg, 2);
  141. // is it the syntax '--option=argument'?
  142. if (strpos($option,'=') !== FALSE)
  143. array_push( $ret['options'], explode('=', $option, 2) );
  144. else
  145. array_push( $ret['options'], $option );
  146. continue;
  147. }
  148. // Is it a flag or a serial of flags? (prefixed with -)
  149. if ( substr( $arg, 0, 1 ) === '-' ) {
  150. for ($i = 1; isset($arg[$i]) ; $i++)
  151. $ret['flags'][] = $arg[$i];
  152. continue;
  153. }
  154. // finally, it is not option, nor flag
  155. $ret['arguments'][] = $arg;
  156. continue;
  157. }
  158. return $ret;
  159. }//function arguments
  160. /**
  161. * ./script.php arg3
  162. * input : arg3 ; return true
  163. * input : arg4 ; return false
  164. * @param unknown_type $argument
  165. * @return bool
  166. */
  167. function getArg($arg){
  168. $args = $this::parseArgs();
  169. if(in_array($arg, $args)){
  170. return true;
  171. }else{
  172. return false;
  173. }
  174. }
  175. /**
  176. * Checks if a certain option is set and returns the string.
  177. * ./script --opt1
  178. * @param unknown_type $option
  179. */
  180. function getOption($option){
  181. //$args = $this->parseArgs();
  182. //return $args['options'][$option];
  183. }
  184. //-h
  185. private function flag_h($opt = null){
  186. if($opt == 'help'){
  187. return 'Display help.';
  188. }
  189. $this->help();
  190. }
  191. // ./script.php help
  192. private function argument_help($opt = null){
  193. if($opt == 'help'){
  194. return 'Display help.';
  195. }
  196. $this->help();
  197. }
  198. /**
  199. * ./script.php --option1 --option1=var1 => array('options' => array( 0 => 'option1', array('0' => 'option1', '1' => 'var1'))
  200. *
  201. * @param unknown_type $opt
  202. */
  203. private function option_help($opt = null){
  204. if($opt == 'help'){
  205. return 'Display help for a specific command. ?=command';
  206. }
  207. if(substr($opt, 0, 2) == '--'){
  208. $opt = str_replace('--', '', $opt);
  209. //option
  210. $method = 'option_'.$opt;
  211. }elseif(substr($opt, 0, 1) == '-'){
  212. //flag
  213. $opt = str_replace('-', '', $opt);
  214. $method = 'flag_'.$opt;
  215. }else{
  216. //argument
  217. $method = 'argument_'.$opt;
  218. }
  219. if(method_exists($this, $method)){
  220. print "\n".$this->$method('help')."\n\n";
  221. }elseif($opt == null){
  222. $this->help();
  223. }else{
  224. print "\n".'Option, argument or flag not found.'."\n\n";
  225. }
  226. }
  227. /**
  228. * print out help
  229. */
  230. public function help($args = array()){
  231. print $this->colorText($this->appname, "LIGHT_RED")."\n--------------\n";
  232. $methods = get_class_methods(get_class($this));
  233. foreach($methods as $method){
  234. if(substr($method,0, 4) == 'flag'){
  235. $flag = str_replace('flag_', '', $method);
  236. $flags_help[$flag] = $this->$method('help');
  237. }elseif(substr($method,0, 8) == 'argument'){
  238. $argument = str_replace('argument_', '', $method);
  239. $arguments_help[$argument] = $this->$method('help');
  240. }elseif(substr($method,0, 6) == 'option'){
  241. $option = str_replace('option_', '', $method);
  242. $options_help[$option] = $this->$method('help');
  243. }
  244. }
  245. print $this->colorText(' Flags:', "BLUE")."\n";
  246. foreach($flags_help as $flag => $desc){
  247. $spaces = 20 - strlen($flag);
  248. printf(" -%s%".$spaces."s%s\n", $flag,'', $desc);
  249. }
  250. print "\n".$this->colorText(' Arguments:', "BLUE")."\n";
  251. foreach($arguments_help as $arg => $desc){
  252. $spaces = 20 - strlen($arg) + 1;
  253. printf(" %s%".$spaces."s%s\n", $arg,'', $desc);
  254. }
  255. print "\n".$this->colorText(' Options:', "BLUE")."\n";
  256. foreach($options_help as $opt => $desc){
  257. $spaces = 20 - strlen($opt) - strlen($opt) - 4;
  258. printf(" --%s;%s=?%".$spaces."s%s\n",$opt, $opt,'', $desc);
  259. }
  260. print "\n";
  261. exit();
  262. }
  263. # first define colors to use
  264. private $_colors = array(
  265. "LIGHT_RED" => "[1;31m",
  266. "LIGHT_GREEN" => "[1;32m",
  267. "YELLOW" => "[1;33m",
  268. "LIGHT_BLUE" => "[1;34m",
  269. "MAGENTA" => "[1;35m",
  270. "LIGHT_CYAN" => "[1;36m",
  271. "WHITE" => "[1;37m",
  272. "NORMAL" => "[0m",
  273. "BLACK" => "[0;30m",
  274. "RED" => "[0;31m",
  275. "GREEN" => "[0;32m",
  276. "BROWN" => "[0;33m",
  277. "BLUE" => "[0;34m",
  278. "CYAN" => "[0;36m",
  279. "BOLD" => "[1m",
  280. "UNDERSCORE" => "[4m",
  281. "REVERSE" => "[7m",
  282. );
  283. ##############################################
  284. # Output colorized text to terminal run
  285. # php scripts..
  286. ##############################################
  287. function colorText($text, $color="NORMAL", $back=1){
  288. $out = $this->_colors[$color];
  289. if($out == ""){
  290. $out = "[0m";
  291. }
  292. if($back){
  293. return chr(27)."$out$text".chr(27)."[0m";#.chr(27);
  294. }else{
  295. echo chr(27)."$out$text".chr(27).chr(27)."[0m";#.chr(27);
  296. }//fi
  297. }// end function
  298. ##############################################
  299. }