PageRenderTime 106ms CodeModel.GetById 60ms app.highlight 17ms RepoModel.GetById 13ms app.codeStats 1ms

/yii/console/CConsoleCommand.php

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