123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599 |
- <?php
- abstract class CConsoleCommand extends CComponent
- {
-
- public $defaultAction='index';
- private $_name;
- private $_runner;
-
- public function __construct($name,$runner)
- {
- $this->_name=$name;
- $this->_runner=$runner;
- $this->attachBehaviors($this->behaviors());
- }
-
- public function init()
- {
- }
-
- public function behaviors()
- {
- return array();
- }
-
- public function run($args)
- {
- list($action, $options, $args)=$this->resolveRequest($args);
- $methodName='action'.$action;
- if(!preg_match('/^\w+$/',$action) || !method_exists($this,$methodName))
- $this->usageError("Unknown action: ".$action);
- $method=new ReflectionMethod($this,$methodName);
- $params=array();
-
- foreach($method->getParameters() as $i=>$param)
- {
- $name=$param->getName();
- if(isset($options[$name]))
- {
- if($param->isArray())
- $params[]=is_array($options[$name]) ? $options[$name] : array($options[$name]);
- elseif(!is_array($options[$name]))
- $params[]=$options[$name];
- else
- $this->usageError("Option --$name requires a scalar. Array is given.");
- }
- elseif($name==='args')
- $params[]=$args;
- elseif($param->isDefaultValueAvailable())
- $params[]=$param->getDefaultValue();
- else
- $this->usageError("Missing required option --$name.");
- unset($options[$name]);
- }
-
- if(!empty($options))
- {
- $class=new ReflectionClass(get_class($this));
- foreach($options as $name=>$value)
- {
- if($class->hasProperty($name))
- {
- $property=$class->getProperty($name);
- if($property->isPublic() && !$property->isStatic())
- {
- $this->$name=$value;
- unset($options[$name]);
- }
- }
- }
- }
- if(!empty($options))
- $this->usageError("Unknown options: ".implode(', ',array_keys($options)));
- $exitCode=0;
- if($this->beforeAction($action,$params))
- {
- $exitCode=$method->invokeArgs($this,$params);
- $exitCode=$this->afterAction($action,$params,is_int($exitCode)?$exitCode:0);
- }
- return $exitCode;
- }
-
- protected function beforeAction($action,$params)
- {
- if($this->hasEventHandler('onBeforeAction'))
- {
- $event = new CConsoleCommandEvent($this,$params,$action);
- $this->onBeforeAction($event);
- return !$event->stopCommand;
- }
- else
- {
- return true;
- }
- }
-
- protected function afterAction($action,$params,$exitCode=0)
- {
- $event=new CConsoleCommandEvent($this,$params,$action,$exitCode);
- if($this->hasEventHandler('onAfterAction'))
- $this->onAfterAction($event);
- return $event->exitCode;
- }
-
- protected function resolveRequest($args)
- {
- $options=array();
- $params=array();
- foreach($args as $arg)
- {
- if(preg_match('/^--(\w+)(=(.*))?$/',$arg,$matches))
- {
- $name=$matches[1];
- $value=isset($matches[3]) ? $matches[3] : true;
- if(isset($options[$name]))
- {
- if(!is_array($options[$name]))
- $options[$name]=array($options[$name]);
- $options[$name][]=$value;
- }
- else
- $options[$name]=$value;
- }
- elseif(isset($action))
- $params[]=$arg;
- else
- $action=$arg;
- }
- if(!isset($action))
- $action=$this->defaultAction;
- return array($action,$options,$params);
- }
-
- public function getName()
- {
- return $this->_name;
- }
-
- public function getCommandRunner()
- {
- return $this->_runner;
- }
-
- public function getHelp()
- {
- $help='Usage: '.$this->getCommandRunner()->getScriptName().' '.$this->getName();
- $options=$this->getOptionHelp();
- if(empty($options))
- return $help."\n";
- if(count($options)===1)
- return $help.' '.$options[0]."\n";
- $help.=" <action>\nActions:\n";
- foreach($options as $option)
- $help.=' '.$option."\n";
- return $help;
- }
-
- public function getOptionHelp()
- {
- $options=array();
- $class=new ReflectionClass(get_class($this));
- foreach($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method)
- {
- $name=$method->getName();
- if(!strncasecmp($name,'action',6) && strlen($name)>6)
- {
- $name=substr($name,6);
- $name[0]=strtolower($name[0]);
- $help=$name;
- foreach($method->getParameters() as $param)
- {
- $optional=$param->isDefaultValueAvailable();
- $defaultValue=$optional ? $param->getDefaultValue() : null;
- if(is_array($defaultValue)) {
- $defaultValue = str_replace(array("\r\n", "\n", "\r"), "", print_r($defaultValue, true));
- }
- $name=$param->getName();
- if($name==='args')
- continue;
- if($optional)
- $help.=" [--$name=$defaultValue]";
- else
- $help.=" --$name=value";
- }
- $options[]=$help;
- }
- }
- return $options;
- }
-
- public function usageError($message)
- {
- echo "Error: $message\n\n".$this->getHelp()."\n";
- exit(1);
- }
-
- public function copyFiles($fileList)
- {
- $overwriteAll=false;
- foreach($fileList as $name=>$file)
- {
- $source=strtr($file['source'],'/\\',DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR);
- $target=strtr($file['target'],'/\\',DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR);
- $callback=isset($file['callback']) ? $file['callback'] : null;
- $params=isset($file['params']) ? $file['params'] : null;
- if(is_dir($source))
- {
- $this->ensureDirectory($target);
- continue;
- }
- if($callback!==null)
- $content=call_user_func($callback,$source,$params);
- else
- $content=file_get_contents($source);
- if(is_file($target))
- {
- if($content===file_get_contents($target))
- {
- echo " unchanged $name\n";
- continue;
- }
- if($overwriteAll)
- echo " overwrite $name\n";
- else
- {
- echo " exist $name\n";
- echo " ...overwrite? [Yes|No|All|Quit] ";
- $answer=trim(fgets(STDIN));
- if(!strncasecmp($answer,'q',1))
- return;
- elseif(!strncasecmp($answer,'y',1))
- echo " overwrite $name\n";
- elseif(!strncasecmp($answer,'a',1))
- {
- echo " overwrite $name\n";
- $overwriteAll=true;
- }
- else
- {
- echo " skip $name\n";
- continue;
- }
- }
- }
- else
- {
- $this->ensureDirectory(dirname($target));
- echo " generate $name\n";
- }
- file_put_contents($target,$content);
- }
- }
-
- public function buildFileList($sourceDir, $targetDir, $baseDir='', $ignoreFiles=array(), $renameMap=array())
- {
- $list=array();
- $handle=opendir($sourceDir);
- while(($file=readdir($handle))!==false)
- {
- if(in_array($file,array('.','..','.svn','.gitignore')) || in_array($file,$ignoreFiles))
- continue;
- $sourcePath=$sourceDir.DIRECTORY_SEPARATOR.$file;
- $targetPath=$targetDir.DIRECTORY_SEPARATOR.strtr($file,$renameMap);
- $name=$baseDir===''?$file : $baseDir.'/'.$file;
- $list[$name]=array('source'=>$sourcePath, 'target'=>$targetPath);
- if(is_dir($sourcePath))
- $list=array_merge($list,$this->buildFileList($sourcePath,$targetPath,$name,$ignoreFiles,$renameMap));
- }
- closedir($handle);
- return $list;
- }
-
- public function ensureDirectory($directory)
- {
- if(!is_dir($directory))
- {
- $this->ensureDirectory(dirname($directory));
- echo " mkdir ".strtr($directory,'\\','/')."\n";
- mkdir($directory);
- }
- }
-
- public function renderFile($_viewFile_,$_data_=null,$_return_=false)
- {
- if(is_array($_data_))
- extract($_data_,EXTR_PREFIX_SAME,'data');
- else
- $data=$_data_;
- if($_return_)
- {
- ob_start();
- ob_implicit_flush(false);
- require($_viewFile_);
- return ob_get_clean();
- }
- else
- require($_viewFile_);
- }
-
- public function pluralize($name)
- {
- $rules=array(
- '/(m)ove$/i' => '\1oves',
- '/(f)oot$/i' => '\1eet',
- '/(c)hild$/i' => '\1hildren',
- '/(h)uman$/i' => '\1umans',
- '/(m)an$/i' => '\1en',
- '/(s)taff$/i' => '\1taff',
- '/(t)ooth$/i' => '\1eeth',
- '/(p)erson$/i' => '\1eople',
- '/([m|l])ouse$/i' => '\1ice',
- '/(x|ch|ss|sh|us|as|is|os)$/i' => '\1es',
- '/([^aeiouy]|qu)y$/i' => '\1ies',
- '/(?:([^f])fe|([lr])f)$/i' => '\1\2ves',
- '/(shea|lea|loa|thie)f$/i' => '\1ves',
- '/([ti])um$/i' => '\1a',
- '/(tomat|potat|ech|her|vet)o$/i' => '\1oes',
- '/(bu)s$/i' => '\1ses',
- '/(ax|test)is$/i' => '\1es',
- '/s$/' => 's',
- );
- foreach($rules as $rule=>$replacement)
- {
- if(preg_match($rule,$name))
- return preg_replace($rule,$replacement,$name);
- }
- return $name.'s';
- }
-
- public function prompt($message,$default=null)
- {
- if($default!==null)
- $message.=" [$default] ";
- else
- $message.=' ';
- if(extension_loaded('readline'))
- {
- $input=readline($message);
- if($input!==false)
- readline_add_history($input);
- }
- else
- {
- echo $message;
- $input=fgets(STDIN);
- }
- if($input===false)
- return false;
- else{
- $input=trim($input);
- return ($input==='' && $default!==null) ? $default : $input;
- }
- }
-
- public function confirm($message,$default=false)
- {
- echo $message.' (yes|no) [' . ($default ? 'yes' : 'no') . ']:';
- $input = trim(fgets(STDIN));
- return empty($input) ? $default : !strncasecmp($input,'y',1);
- }
-
- public function onBeforeAction($event)
- {
- $this->raiseEvent('onBeforeAction',$event);
- }
-
- public function onAfterAction($event)
- {
- $this->raiseEvent('onAfterAction',$event);
- }
- }
|