PageRenderTime 50ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/yii/framework/console/CConsoleCommand.php

https://bitbucket.org/ddonthula/zurmoemail
PHP | 591 lines | 365 code | 31 blank | 195 comment | 39 complexity | 64444fcdddc125aa0a33aa6e27fa6784 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0, LGPL-2.1, BSD-2-Clause, GPL-2.0, GPL-3.0
  1. <?php
  2. /**
  3. * CConsoleCommand class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2011 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 {
  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;
  261. if(count($options)===1)
  262. return $help.' '.$options[0];
  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. $name=$param->getName();
  293. if($optional)
  294. $help.=" [--$name=$defaultValue]";
  295. else
  296. $help.=" --$name=value";
  297. }
  298. $options[]=$help;
  299. }
  300. }
  301. return $options;
  302. }
  303. /**
  304. * Displays a usage error.
  305. * This method will then terminate the execution of the current application.
  306. * @param string $message the error message
  307. */
  308. public function usageError($message)
  309. {
  310. echo "Error: $message\n\n".$this->getHelp()."\n";
  311. exit(1);
  312. }
  313. /**
  314. * Copies a list of files from one place to another.
  315. * @param array $fileList the list of files to be copied (name=>spec).
  316. * The array keys are names displayed during the copy process, and array values are specifications
  317. * for files to be copied. Each array value must be an array of the following structure:
  318. * <ul>
  319. * <li>source: required, the full path of the file/directory to be copied from</li>
  320. * <li>target: required, the full path of the file/directory to be copied to</li>
  321. * <li>callback: optional, the callback to be invoked when copying a file. The callback function
  322. * should be declared as follows:
  323. * <pre>
  324. * function foo($source,$params)
  325. * </pre>
  326. * where $source parameter is the source file path, and the content returned
  327. * by the function will be saved into the target file.</li>
  328. * <li>params: optional, the parameters to be passed to the callback</li>
  329. * </ul>
  330. * @see buildFileList
  331. */
  332. public function copyFiles($fileList)
  333. {
  334. $overwriteAll=false;
  335. foreach($fileList as $name=>$file)
  336. {
  337. $source=strtr($file['source'],'/\\',DIRECTORY_SEPARATOR);
  338. $target=strtr($file['target'],'/\\',DIRECTORY_SEPARATOR);
  339. $callback=isset($file['callback']) ? $file['callback'] : null;
  340. $params=isset($file['params']) ? $file['params'] : null;
  341. if(is_dir($source))
  342. {
  343. $this->ensureDirectory($target);
  344. continue;
  345. }
  346. if($callback!==null)
  347. $content=call_user_func($callback,$source,$params);
  348. else
  349. $content=file_get_contents($source);
  350. if(is_file($target))
  351. {
  352. if($content===file_get_contents($target))
  353. {
  354. echo " unchanged $name\n";
  355. continue;
  356. }
  357. if($overwriteAll)
  358. echo " overwrite $name\n";
  359. else
  360. {
  361. echo " exist $name\n";
  362. echo " ...overwrite? [Yes|No|All|Quit] ";
  363. $answer=trim(fgets(STDIN));
  364. if(!strncasecmp($answer,'q',1))
  365. return;
  366. elseif(!strncasecmp($answer,'y',1))
  367. echo " overwrite $name\n";
  368. elseif(!strncasecmp($answer,'a',1))
  369. {
  370. echo " overwrite $name\n";
  371. $overwriteAll=true;
  372. }
  373. else
  374. {
  375. echo " skip $name\n";
  376. continue;
  377. }
  378. }
  379. }
  380. else
  381. {
  382. $this->ensureDirectory(dirname($target));
  383. echo " generate $name\n";
  384. }
  385. file_put_contents($target,$content);
  386. }
  387. }
  388. /**
  389. * Builds the file list of a directory.
  390. * This method traverses through the specified directory and builds
  391. * a list of files and subdirectories that the directory contains.
  392. * The result of this function can be passed to {@link copyFiles}.
  393. * @param string $sourceDir the source directory
  394. * @param string $targetDir the target directory
  395. * @param string $baseDir base directory
  396. * @param array $ignoreFiles list of the names of files that should
  397. * be ignored in list building process. Argument available since 1.1.11.
  398. * @param array $renameMap hash array of file names that should be
  399. * renamed. Example value: array('1.old.txt'=>'2.new.txt').
  400. * Argument available since 1.1.11.
  401. * @return array the file list (see {@link copyFiles})
  402. */
  403. public function buildFileList($sourceDir, $targetDir, $baseDir='', $ignoreFiles=array(), $renameMap=array())
  404. {
  405. $list=array();
  406. $handle=opendir($sourceDir);
  407. while(($file=readdir($handle))!==false)
  408. {
  409. if(in_array($file,array('.','..','.svn','.gitignore')) || in_array($file,$ignoreFiles))
  410. continue;
  411. $sourcePath=$sourceDir.DIRECTORY_SEPARATOR.$file;
  412. $targetPath=$targetDir.DIRECTORY_SEPARATOR.strtr($file,$renameMap);
  413. $name=$baseDir===''?$file : $baseDir.'/'.$file;
  414. $list[$name]=array('source'=>$sourcePath, 'target'=>$targetPath);
  415. if(is_dir($sourcePath))
  416. $list=array_merge($list,$this->buildFileList($sourcePath,$targetPath,$name,$ignoreFiles,$renameMap));
  417. }
  418. closedir($handle);
  419. return $list;
  420. }
  421. /**
  422. * Creates all parent directories if they do not exist.
  423. * @param string $directory the directory to be checked
  424. */
  425. public function ensureDirectory($directory)
  426. {
  427. if(!is_dir($directory))
  428. {
  429. $this->ensureDirectory(dirname($directory));
  430. echo " mkdir ".strtr($directory,'\\','/')."\n";
  431. mkdir($directory);
  432. }
  433. }
  434. /**
  435. * Renders a view file.
  436. * @param string $_viewFile_ view file path
  437. * @param array $_data_ optional data to be extracted as local view variables
  438. * @param boolean $_return_ whether to return the rendering result instead of displaying it
  439. * @return mixed the rendering result if required. Null otherwise.
  440. */
  441. public function renderFile($_viewFile_,$_data_=null,$_return_=false)
  442. {
  443. if(is_array($_data_))
  444. extract($_data_,EXTR_PREFIX_SAME,'data');
  445. else
  446. $data=$_data_;
  447. if($_return_)
  448. {
  449. ob_start();
  450. ob_implicit_flush(false);
  451. require($_viewFile_);
  452. return ob_get_clean();
  453. }
  454. else
  455. require($_viewFile_);
  456. }
  457. /**
  458. * Converts a word to its plural form.
  459. * @param string $name the word to be pluralized
  460. * @return string the pluralized word
  461. */
  462. public function pluralize($name)
  463. {
  464. $rules=array(
  465. '/(m)ove$/i' => '\1oves',
  466. '/(f)oot$/i' => '\1eet',
  467. '/(c)hild$/i' => '\1hildren',
  468. '/(h)uman$/i' => '\1umans',
  469. '/(m)an$/i' => '\1en',
  470. '/(t)ooth$/i' => '\1eeth',
  471. '/(p)erson$/i' => '\1eople',
  472. '/([m|l])ouse$/i' => '\1ice',
  473. '/(x|ch|ss|sh|us|as|is|os)$/i' => '\1es',
  474. '/([^aeiouy]|qu)y$/i' => '\1ies',
  475. '/(?:([^f])fe|([lr])f)$/i' => '\1\2ves',
  476. '/(shea|lea|loa|thie)f$/i' => '\1ves',
  477. '/([ti])um$/i' => '\1a',
  478. '/(tomat|potat|ech|her|vet)o$/i' => '\1oes',
  479. '/(bu)s$/i' => '\1ses',
  480. '/(ax|test)is$/i' => '\1es',
  481. '/s$/' => 's',
  482. );
  483. foreach($rules as $rule=>$replacement)
  484. {
  485. if(preg_match($rule,$name))
  486. return preg_replace($rule,$replacement,$name);
  487. }
  488. return $name.'s';
  489. }
  490. /**
  491. * Reads input via the readline PHP extension if that's available, or fgets() if readline is not installed.
  492. *
  493. * @param string $message to echo out before waiting for user input
  494. * @param string $default the default string to be returned when user does not write anything.
  495. * Defaults to null, means that default string is disabled. This parameter is available since version 1.1.11.
  496. * @return mixed line read as a string, or false if input has been closed
  497. *
  498. * @since 1.1.9
  499. */
  500. public function prompt($message,$default=null)
  501. {
  502. if($default!==null)
  503. $message.=" [$default] ";
  504. else
  505. $message.=' ';
  506. if(extension_loaded('readline'))
  507. {
  508. $input=readline($message);
  509. if($input!==false)
  510. readline_add_history($input);
  511. }
  512. else
  513. {
  514. echo $message;
  515. $input=fgets(STDIN);
  516. }
  517. if($input===false)
  518. return false;
  519. else{
  520. $input=trim($input);
  521. return ($input==='' && $default!==null) ? $default : $input;
  522. }
  523. }
  524. /**
  525. * Asks user to confirm by typing y or n.
  526. *
  527. * @param string $message to echo out before waiting for user input
  528. * @param boolean $default this value is returned if no selection is made. This parameter has been available since version 1.1.11.
  529. * @return boolean whether user confirmed
  530. *
  531. * @since 1.1.9
  532. */
  533. public function confirm($message,$default=false)
  534. {
  535. echo $message.' (yes|no) [' . ($default ? 'yes' : 'no') . ']:';
  536. $input = trim(fgets(STDIN));
  537. return empty($input) ? $default : !strncasecmp($input,'y',1);
  538. }
  539. /**
  540. * This event is raised before an action is to be executed.
  541. * @param CConsoleCommandEvent $event the event parameter
  542. * @since 1.1.11
  543. */
  544. public function onBeforeAction($event)
  545. {
  546. $this->raiseEvent('onBeforeAction',$event);
  547. }
  548. /**
  549. * This event is raised after an action finishes execution.
  550. * @param CConsoleCommandEvent $event the event parameter
  551. * @since 1.1.11
  552. */
  553. public function onAfterAction($event)
  554. {
  555. $this->raiseEvent('onAfterAction',$event);
  556. }
  557. }