CConsoleCommand.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. <?php
  2. /**
  3. * CConsoleCommand class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CConsoleCommand represents an executable console command.
  12. *
  13. * It works like {@link CController} by parsing command line options and dispatching
  14. * the request to a specific action with appropriate option values.
  15. *
  16. * Users call a console command via the following command format:
  17. * <pre>
  18. * yiic CommandName ActionName --Option1=Value1 --Option2=Value2 ...
  19. * </pre>
  20. *
  21. * Child classes mainly needs to implement various action methods whose name must be
  22. * prefixed with "action". The parameters to an action method are considered as options
  23. * for that specific action. The action specified as {@link defaultAction} will be invoked
  24. * when a user does not specify the action name in his command.
  25. *
  26. * Options are bound to action parameters via parameter names. For example, the following
  27. * action method will allow us to run a command with <code>yiic sitemap --type=News</code>:
  28. * <pre>
  29. * class SitemapCommand extends CConsoleCommand {
  30. * public function actionIndex($type) {
  31. * ....
  32. * }
  33. * }
  34. * </pre>
  35. *
  36. * Since version 1.1.11 the return value of action methods will be used as application exit code if it is an integer value.
  37. *
  38. * @property string $name The command name.
  39. * @property CConsoleCommandRunner $commandRunner The command runner instance.
  40. * @property string $help The command description. Defaults to 'Usage: php entry-script.php command-name'.
  41. * @property array $optionHelp The command option help information. Each array element describes
  42. * the help information for a single action.
  43. *
  44. * @author Qiang Xue <qiang.xue@gmail.com>
  45. * @package system.console
  46. * @since 1.0
  47. */
  48. abstract class CConsoleCommand extends CComponent
  49. {
  50. /**
  51. * @var string the name of the default action. Defaults to 'index'.
  52. * @since 1.1.5
  53. */
  54. public $defaultAction='index';
  55. private $_name;
  56. private $_runner;
  57. /**
  58. * Constructor.
  59. * @param string $name name of the command
  60. * @param CConsoleCommandRunner $runner the command runner
  61. */
  62. public function __construct($name,$runner)
  63. {
  64. $this->_name=$name;
  65. $this->_runner=$runner;
  66. $this->attachBehaviors($this->behaviors());
  67. }
  68. /**
  69. * Initializes the command object.
  70. * This method is invoked after a command object is created and initialized with configurations.
  71. * You may override this method to further customize the command before it executes.
  72. * @since 1.1.6
  73. */
  74. public function init()
  75. {
  76. }
  77. /**
  78. * Returns a list of behaviors that this command should behave as.
  79. * The return value should be an array of behavior configurations indexed by
  80. * behavior names. Each behavior configuration can be either a string specifying
  81. * the behavior class or an array of the following structure:
  82. * <pre>
  83. * 'behaviorName'=>array(
  84. * 'class'=>'path.to.BehaviorClass',
  85. * 'property1'=>'value1',
  86. * 'property2'=>'value2',
  87. * )
  88. * </pre>
  89. *
  90. * Note, the behavior classes must implement {@link IBehavior} or extend from
  91. * {@link CBehavior}. Behaviors declared in this method will be attached
  92. * to the controller when it is instantiated.
  93. *
  94. * For more details about behaviors, see {@link CComponent}.
  95. * @return array the behavior configurations (behavior name=>behavior configuration)
  96. * @since 1.1.11
  97. */
  98. public function behaviors()
  99. {
  100. return array();
  101. }
  102. /**
  103. * Executes the command.
  104. * The default implementation will parse the input parameters and
  105. * dispatch the command request to an appropriate action with the corresponding
  106. * option values
  107. * @param array $args command line parameters for this command.
  108. * @return integer application exit code, which is returned by the invoked action. 0 if the action did not return anything.
  109. * (return value is available since version 1.1.11)
  110. */
  111. public function run($args)
  112. {
  113. list($action, $options, $args)=$this->resolveRequest($args);
  114. $methodName='action'.$action;
  115. if(!preg_match('/^\w+$/',$action) || !method_exists($this,$methodName))
  116. $this->usageError("Unknown action: ".$action);
  117. $method=new ReflectionMethod($this,$methodName);
  118. $params=array();
  119. // named and unnamed options
  120. foreach($method->getParameters() as $i=>$param)
  121. {
  122. $name=$param->getName();
  123. if(isset($options[$name]))
  124. {
  125. if($param->isArray())
  126. $params[]=is_array($options[$name]) ? $options[$name] : array($options[$name]);
  127. elseif(!is_array($options[$name]))
  128. $params[]=$options[$name];
  129. else
  130. $this->usageError("Option --$name requires a scalar. Array is given.");
  131. }
  132. elseif($name==='args')
  133. $params[]=$args;
  134. elseif($param->isDefaultValueAvailable())
  135. $params[]=$param->getDefaultValue();
  136. else
  137. $this->usageError("Missing required option --$name.");
  138. unset($options[$name]);
  139. }
  140. // try global options
  141. if(!empty($options))
  142. {
  143. $class=new ReflectionClass(get_class($this));
  144. foreach($options as $name=>$value)
  145. {
  146. if($class->hasProperty($name))
  147. {
  148. $property=$class->getProperty($name);
  149. if($property->isPublic() && !$property->isStatic())
  150. {
  151. $this->$name=$value;
  152. unset($options[$name]);
  153. }
  154. }
  155. }
  156. }
  157. if(!empty($options))
  158. $this->usageError("Unknown options: ".implode(', ',array_keys($options)));
  159. $exitCode=0;
  160. if($this->beforeAction($action,$params))
  161. {
  162. $exitCode=$method->invokeArgs($this,$params);
  163. $exitCode=$this->afterAction($action,$params,is_int($exitCode)?$exitCode:0);
  164. }
  165. return $exitCode;
  166. }
  167. /**
  168. * This method is invoked right before an action is to be executed.
  169. * You may override this method to do last-minute preparation for the action.
  170. * @param string $action the action name
  171. * @param array $params the parameters to be passed to the action method.
  172. * @return boolean whether the action should be executed.
  173. */
  174. protected function beforeAction($action,$params)
  175. {
  176. if($this->hasEventHandler('onBeforeAction'))
  177. {
  178. $event = new CConsoleCommandEvent($this,$params,$action);
  179. $this->onBeforeAction($event);
  180. return !$event->stopCommand;
  181. }
  182. else
  183. {
  184. return true;
  185. }
  186. }
  187. /**
  188. * This method is invoked right after an action finishes execution.
  189. * You may override this method to do some postprocessing for the action.
  190. * @param string $action the action name
  191. * @param array $params the parameters to be passed to the action method.
  192. * @param integer $exitCode the application exit code returned by the action method.
  193. * @return integer application exit code (return value is available since version 1.1.11)
  194. */
  195. protected function afterAction($action,$params,$exitCode=0)
  196. {
  197. $event=new CConsoleCommandEvent($this,$params,$action,$exitCode);
  198. if($this->hasEventHandler('onAfterAction'))
  199. $this->onAfterAction($event);
  200. return $event->exitCode;
  201. }
  202. /**
  203. * Parses the command line arguments and determines which action to perform.
  204. * @param array $args command line arguments
  205. * @return array the action name, named options (name=>value), and unnamed options
  206. * @since 1.1.5
  207. */
  208. protected function resolveRequest($args)
  209. {
  210. $options=array(); // named parameters
  211. $params=array(); // unnamed parameters
  212. foreach($args as $arg)
  213. {
  214. if(preg_match('/^--(\w+)(=(.*))?$/',$arg,$matches)) // an option
  215. {
  216. $name=$matches[1];
  217. $value=isset($matches[3]) ? $matches[3] : true;
  218. if(isset($options[$name]))
  219. {
  220. if(!is_array($options[$name]))
  221. $options[$name]=array($options[$name]);
  222. $options[$name][]=$value;
  223. }
  224. else
  225. $options[$name]=$value;
  226. }
  227. elseif(isset($action))
  228. $params[]=$arg;
  229. else
  230. $action=$arg;
  231. }
  232. if(!isset($action))
  233. $action=$this->defaultAction;
  234. return array($action,$options,$params);
  235. }
  236. /**
  237. * @return string the command name.
  238. */
  239. public function getName()
  240. {
  241. return $this->_name;
  242. }
  243. /**
  244. * @return CConsoleCommandRunner the command runner instance
  245. */
  246. public function getCommandRunner()
  247. {
  248. return $this->_runner;
  249. }
  250. /**
  251. * Provides the command description.
  252. * This method may be overridden to return the actual command description.
  253. * @return string the command description. Defaults to 'Usage: php entry-script.php command-name'.
  254. */
  255. public function getHelp()
  256. {
  257. $help='Usage: '.$this->getCommandRunner()->getScriptName().' '.$this->getName();
  258. $options=$this->getOptionHelp();
  259. if(empty($options))
  260. return $help."\n";
  261. if(count($options)===1)
  262. return $help.' '.$options[0]."\n";
  263. $help.=" <action>\nActions:\n";
  264. foreach($options as $option)
  265. $help.=' '.$option."\n";
  266. return $help;
  267. }
  268. /**
  269. * Provides the command option help information.
  270. * The default implementation will return all available actions together with their
  271. * corresponding option information.
  272. * @return array the command option help information. Each array element describes
  273. * the help information for a single action.
  274. * @since 1.1.5
  275. */
  276. public function getOptionHelp()
  277. {
  278. $options=array();
  279. $class=new ReflectionClass(get_class($this));
  280. foreach($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method)
  281. {
  282. $name=$method->getName();
  283. if(!strncasecmp($name,'action',6) && strlen($name)>6)
  284. {
  285. $name=substr($name,6);
  286. $name[0]=strtolower($name[0]);
  287. $help=$name;
  288. foreach($method->getParameters() as $param)
  289. {
  290. $optional=$param->isDefaultValueAvailable();
  291. $defaultValue=$optional ? $param->getDefaultValue() : null;
  292. if(is_array($defaultValue)) {
  293. $defaultValue = str_replace(array("\r\n", "\n", "\r"), "", print_r($defaultValue, true));
  294. }
  295. $name=$param->getName();
  296. if($name==='args')
  297. continue;
  298. if($optional)
  299. $help.=" [--$name=$defaultValue]";
  300. else
  301. $help.=" --$name=value";
  302. }
  303. $options[]=$help;
  304. }
  305. }
  306. return $options;
  307. }
  308. /**
  309. * Displays a usage error.
  310. * This method will then terminate the execution of the current application.
  311. * @param string $message the error message
  312. */
  313. public function usageError($message)
  314. {
  315. echo "Error: $message\n\n".$this->getHelp()."\n";
  316. exit(1);
  317. }
  318. /**
  319. * Copies a list of files from one place to another.
  320. * @param array $fileList the list of files to be copied (name=>spec).
  321. * The array keys are names displayed during the copy process, and array values are specifications
  322. * for files to be copied. Each array value must be an array of the following structure:
  323. * <ul>
  324. * <li>source: required, the full path of the file/directory to be copied from</li>
  325. * <li>target: required, the full path of the file/directory to be copied to</li>
  326. * <li>callback: optional, the callback to be invoked when copying a file. The callback function
  327. * should be declared as follows:
  328. * <pre>
  329. * function foo($source,$params)
  330. * </pre>
  331. * where $source parameter is the source file path, and the content returned
  332. * by the function will be saved into the target file.</li>
  333. * <li>params: optional, the parameters to be passed to the callback</li>
  334. * </ul>
  335. * @see buildFileList
  336. */
  337. public function copyFiles($fileList)
  338. {
  339. $overwriteAll=false;
  340. foreach($fileList as $name=>$file)
  341. {
  342. $source=strtr($file['source'],'/\\',DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR);
  343. $target=strtr($file['target'],'/\\',DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR);
  344. $callback=isset($file['callback']) ? $file['callback'] : null;
  345. $params=isset($file['params']) ? $file['params'] : null;
  346. if(is_dir($source))
  347. {
  348. $this->ensureDirectory($target);
  349. continue;
  350. }
  351. if($callback!==null)
  352. $content=call_user_func($callback,$source,$params);
  353. else
  354. $content=file_get_contents($source);
  355. if(is_file($target))
  356. {
  357. if($content===file_get_contents($target))
  358. {
  359. echo " unchanged $name\n";
  360. continue;
  361. }
  362. if($overwriteAll)
  363. echo " overwrite $name\n";
  364. else
  365. {
  366. echo " exist $name\n";
  367. echo " ...overwrite? [Yes|No|All|Quit] ";
  368. $answer=trim(fgets(STDIN));
  369. if(!strncasecmp($answer,'q',1))
  370. return;
  371. elseif(!strncasecmp($answer,'y',1))
  372. echo " overwrite $name\n";
  373. elseif(!strncasecmp($answer,'a',1))
  374. {
  375. echo " overwrite $name\n";
  376. $overwriteAll=true;
  377. }
  378. else
  379. {
  380. echo " skip $name\n";
  381. continue;
  382. }
  383. }
  384. }
  385. else
  386. {
  387. $this->ensureDirectory(dirname($target));
  388. echo " generate $name\n";
  389. }
  390. file_put_contents($target,$content);
  391. }
  392. }
  393. /**
  394. * Builds the file list of a directory.
  395. * This method traverses through the specified directory and builds
  396. * a list of files and subdirectories that the directory contains.
  397. * The result of this function can be passed to {@link copyFiles}.
  398. * @param string $sourceDir the source directory
  399. * @param string $targetDir the target directory
  400. * @param string $baseDir base directory
  401. * @param array $ignoreFiles list of the names of files that should
  402. * be ignored in list building process. Argument available since 1.1.11.
  403. * @param array $renameMap hash array of file names that should be
  404. * renamed. Example value: array('1.old.txt'=>'2.new.txt').
  405. * Argument available since 1.1.11.
  406. * @return array the file list (see {@link copyFiles})
  407. */
  408. public function buildFileList($sourceDir, $targetDir, $baseDir='', $ignoreFiles=array(), $renameMap=array())
  409. {
  410. $list=array();
  411. $handle=opendir($sourceDir);
  412. while(($file=readdir($handle))!==false)
  413. {
  414. if(in_array($file,array('.','..','.svn','.gitignore')) || in_array($file,$ignoreFiles))
  415. continue;
  416. $sourcePath=$sourceDir.DIRECTORY_SEPARATOR.$file;
  417. $targetPath=$targetDir.DIRECTORY_SEPARATOR.strtr($file,$renameMap);
  418. $name=$baseDir===''?$file : $baseDir.'/'.$file;
  419. $list[$name]=array('source'=>$sourcePath, 'target'=>$targetPath);
  420. if(is_dir($sourcePath))
  421. $list=array_merge($list,$this->buildFileList($sourcePath,$targetPath,$name,$ignoreFiles,$renameMap));
  422. }
  423. closedir($handle);
  424. return $list;
  425. }
  426. /**
  427. * Creates all parent directories if they do not exist.
  428. * @param string $directory the directory to be checked
  429. */
  430. public function ensureDirectory($directory)
  431. {
  432. if(!is_dir($directory))
  433. {
  434. $this->ensureDirectory(dirname($directory));
  435. echo " mkdir ".strtr($directory,'\\','/')."\n";
  436. mkdir($directory);
  437. }
  438. }
  439. /**
  440. * Renders a view file.
  441. * @param string $_viewFile_ view file path
  442. * @param array $_data_ optional data to be extracted as local view variables
  443. * @param boolean $_return_ whether to return the rendering result instead of displaying it
  444. * @return mixed the rendering result if required. Null otherwise.
  445. */
  446. public function renderFile($_viewFile_,$_data_=null,$_return_=false)
  447. {
  448. if(is_array($_data_))
  449. extract($_data_,EXTR_PREFIX_SAME,'data');
  450. else
  451. $data=$_data_;
  452. if($_return_)
  453. {
  454. ob_start();
  455. ob_implicit_flush(false);
  456. require($_viewFile_);
  457. return ob_get_clean();
  458. }
  459. else
  460. require($_viewFile_);
  461. }
  462. /**
  463. * Converts a word to its plural form.
  464. * @param string $name the word to be pluralized
  465. * @return string the pluralized word
  466. */
  467. public function pluralize($name)
  468. {
  469. $rules=array(
  470. '/(m)ove$/i' => '\1oves',
  471. '/(f)oot$/i' => '\1eet',
  472. '/(c)hild$/i' => '\1hildren',
  473. '/(h)uman$/i' => '\1umans',
  474. '/(m)an$/i' => '\1en',
  475. '/(s)taff$/i' => '\1taff',
  476. '/(t)ooth$/i' => '\1eeth',
  477. '/(p)erson$/i' => '\1eople',
  478. '/([m|l])ouse$/i' => '\1ice',
  479. '/(x|ch|ss|sh|us|as|is|os)$/i' => '\1es',
  480. '/([^aeiouy]|qu)y$/i' => '\1ies',
  481. '/(?:([^f])fe|([lr])f)$/i' => '\1\2ves',
  482. '/(shea|lea|loa|thie)f$/i' => '\1ves',
  483. '/([ti])um$/i' => '\1a',
  484. '/(tomat|potat|ech|her|vet)o$/i' => '\1oes',
  485. '/(bu)s$/i' => '\1ses',
  486. '/(ax|test)is$/i' => '\1es',
  487. '/s$/' => 's',
  488. );
  489. foreach($rules as $rule=>$replacement)
  490. {
  491. if(preg_match($rule,$name))
  492. return preg_replace($rule,$replacement,$name);
  493. }
  494. return $name.'s';
  495. }
  496. /**
  497. * Reads input via the readline PHP extension if that's available, or fgets() if readline is not installed.
  498. *
  499. * @param string $message to echo out before waiting for user input
  500. * @param string $default the default string to be returned when user does not write anything.
  501. * Defaults to null, means that default string is disabled. This parameter is available since version 1.1.11.
  502. * @return mixed line read as a string, or false if input has been closed
  503. *
  504. * @since 1.1.9
  505. */
  506. public function prompt($message,$default=null)
  507. {
  508. if($default!==null)
  509. $message.=" [$default] ";
  510. else
  511. $message.=' ';
  512. if(extension_loaded('readline'))
  513. {
  514. $input=readline($message);
  515. if($input!==false)
  516. readline_add_history($input);
  517. }
  518. else
  519. {
  520. echo $message;
  521. $input=fgets(STDIN);
  522. }
  523. if($input===false)
  524. return false;
  525. else{
  526. $input=trim($input);
  527. return ($input==='' && $default!==null) ? $default : $input;
  528. }
  529. }
  530. /**
  531. * Asks user to confirm by typing y or n.
  532. *
  533. * @param string $message to echo out before waiting for user input
  534. * @param boolean $default this value is returned if no selection is made. This parameter has been available since version 1.1.11.
  535. * @return boolean whether user confirmed
  536. *
  537. * @since 1.1.9
  538. */
  539. public function confirm($message,$default=false)
  540. {
  541. echo $message.' (yes|no) [' . ($default ? 'yes' : 'no') . ']:';
  542. $input = trim(fgets(STDIN));
  543. return empty($input) ? $default : !strncasecmp($input,'y',1);
  544. }
  545. /**
  546. * This event is raised before an action is to be executed.
  547. * @param CConsoleCommandEvent $event the event parameter
  548. * @since 1.1.11
  549. */
  550. public function onBeforeAction($event)
  551. {
  552. $this->raiseEvent('onBeforeAction',$event);
  553. }
  554. /**
  555. * This event is raised after an action finishes execution.
  556. * @param CConsoleCommandEvent $event the event parameter
  557. * @since 1.1.11
  558. */
  559. public function onAfterAction($event)
  560. {
  561. $this->raiseEvent('onAfterAction',$event);
  562. }
  563. }