Add yiic console helper

This commit is contained in:
Tanguy Pruvot 2015-07-02 20:27:28 +02:00
parent d8fe695a46
commit 66d613b7ac
10 changed files with 1432 additions and 0 deletions

View file

@ -0,0 +1,200 @@
<?php
/**
* CConsoleApplication class file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008-2013 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
/**
* CConsoleApplication represents a console application.
*
* CConsoleApplication extends {@link CApplication} by providing functionalities
* specific to console requests. In particular, it deals with console requests
* through a command-based approach:
* <ul>
* <li>A console application consists of one or several possible user commands;</li>
* <li>Each user command is implemented as a class extending {@link CConsoleCommand};</li>
* <li>User specifies which command to run on the command line;</li>
* <li>The command processes the user request with the specified parameters.</li>
* </ul>
*
* The command classes reside in the directory {@link getCommandPath commandPath}.
* The name of the class follows the pattern: &lt;command-name&gt;Command, and its
* file name is the same as the class name. For example, the 'ShellCommand' class defines
* a 'shell' command and the class file name is 'ShellCommand.php'.
*
* To run the console application, enter the following on the command line:
* <pre>
* php path/to/entry_script.php <command name> [param 1] [param 2] ...
* </pre>
*
* You may use the following to see help instructions about a command:
* <pre>
* php path/to/entry_script.php help <command name>
* </pre>
*
* @property string $commandPath The directory that contains the command classes. Defaults to 'protected/commands'.
* @property CConsoleCommandRunner $commandRunner The command runner.
* @property CConsoleCommand $command The currently active command.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @package system.console
* @since 1.0
*/
class CConsoleApplication extends CApplication
{
/**
* @var array mapping from command name to command configurations.
* Each command configuration can be either a string or an array.
* If the former, the string should be the file path of the command class.
* If the latter, the array must contain a 'class' element which specifies
* the command's class name or {@link YiiBase::getPathOfAlias class path alias}.
* The rest name-value pairs in the array are used to initialize
* the corresponding command properties. For example,
* <pre>
* array(
* 'email'=>array(
* 'class'=>'path.to.Mailer',
* 'interval'=>3600,
* ),
* 'log'=>'path/to/LoggerCommand.php',
* )
* </pre>
*/
public $commandMap=array();
private $_commandPath;
private $_runner;
/**
* Initializes the application by creating the command runner.
*/
protected function init()
{
parent::init();
if(!isset($_SERVER['argv'])) // || strncasecmp(php_sapi_name(),'cli',3))
die('This script must be run from the command line.');
$this->_runner=$this->createCommandRunner();
$this->_runner->commands=$this->commandMap;
$this->_runner->addCommands($this->getCommandPath());
}
/**
* Processes the user request.
* This method uses a console command runner to handle the particular user command.
* Since version 1.1.11 this method will exit application with an exit code if one is returned by the user command.
*/
public function processRequest()
{
$exitCode=$this->_runner->run($_SERVER['argv']);
if(is_int($exitCode))
$this->end($exitCode);
}
/**
* Creates the command runner instance.
* @return CConsoleCommandRunner the command runner
*/
protected function createCommandRunner()
{
return new CConsoleCommandRunner;
}
/**
* Displays the captured PHP error.
* This method displays the error in console mode when there is
* no active error handler.
* @param integer $code error code
* @param string $message error message
* @param string $file error file
* @param string $line error line
*/
public function displayError($code,$message,$file,$line)
{
echo "PHP Error[$code]: $message\n";
echo " in file $file at line $line\n";
$trace=debug_backtrace();
// skip the first 4 stacks as they do not tell the error position
if(count($trace)>4)
$trace=array_slice($trace,4);
foreach($trace as $i=>$t)
{
if(!isset($t['file']))
$t['file']='unknown';
if(!isset($t['line']))
$t['line']=0;
if(!isset($t['function']))
$t['function']='unknown';
echo "#$i {$t['file']}({$t['line']}): ";
if(isset($t['object']) && is_object($t['object']))
echo get_class($t['object']).'->';
echo "{$t['function']}()\n";
}
}
/**
* Displays the uncaught PHP exception.
* This method displays the exception in console mode when there is
* no active error handler.
* @param Exception $exception the uncaught exception
*/
public function displayException($exception)
{
echo $exception;
}
/**
* @return string the directory that contains the command classes. Defaults to 'protected/commands'.
*/
public function getCommandPath()
{
$applicationCommandPath = $this->getBasePath().DIRECTORY_SEPARATOR.'commands';
if($this->_commandPath===null && file_exists($applicationCommandPath))
$this->setCommandPath($applicationCommandPath);
return $this->_commandPath;
}
/**
* @param string $value the directory that contains the command classes.
* @throws CException if the directory is invalid
*/
public function setCommandPath($value)
{
if(($this->_commandPath=realpath($value))===false || !is_dir($this->_commandPath))
throw new CException(Yii::t('yii','The command path "{path}" is not a valid directory.',
array('{path}'=>$value)));
}
/**
* Returns the command runner.
* @return CConsoleCommandRunner the command runner.
*/
public function getCommandRunner()
{
return $this->_runner;
}
/**
* Returns the currently running command.
* This is shortcut method for {@link CConsoleCommandRunner::getCommand()}.
* @return CConsoleCommand|null the currently active command.
* @since 1.1.14
*/
public function getCommand()
{
return $this->getCommandRunner()->getCommand();
}
/**
* This is shortcut method for {@link CConsoleCommandRunner::setCommand()}.
* @param CConsoleCommand $value the currently active command.
* @since 1.1.14
*/
public function setCommand($value)
{
$this->getCommandRunner()->setCommand($value);
}
}

View file

@ -0,0 +1,599 @@
<?php
/**
* CConsoleCommand class file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008-2013 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
/**
* CConsoleCommand represents an executable console command.
*
* It works like {@link CController} by parsing command line options and dispatching
* the request to a specific action with appropriate option values.
*
* Users call a console command via the following command format:
* <pre>
* yiic CommandName ActionName --Option1=Value1 --Option2=Value2 ...
* </pre>
*
* Child classes mainly needs to implement various action methods whose name must be
* prefixed with "action". The parameters to an action method are considered as options
* for that specific action. The action specified as {@link defaultAction} will be invoked
* when a user does not specify the action name in his command.
*
* Options are bound to action parameters via parameter names. For example, the following
* action method will allow us to run a command with <code>yiic sitemap --type=News</code>:
* <pre>
* class SitemapCommand extends CConsoleCommand {
* public function actionIndex($type) {
* ....
* }
* }
* </pre>
*
* Since version 1.1.11 the return value of action methods will be used as application exit code if it is an integer value.
*
* @property string $name The command name.
* @property CConsoleCommandRunner $commandRunner The command runner instance.
* @property string $help The command description. Defaults to 'Usage: php entry-script.php command-name'.
* @property array $optionHelp The command option help information. Each array element describes
* the help information for a single action.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @package system.console
* @since 1.0
*/
abstract class CConsoleCommand extends CComponent
{
/**
* @var string the name of the default action. Defaults to 'index'.
* @since 1.1.5
*/
public $defaultAction='index';
private $_name;
private $_runner;
/**
* Constructor.
* @param string $name name of the command
* @param CConsoleCommandRunner $runner the command runner
*/
public function __construct($name,$runner)
{
$this->_name=$name;
$this->_runner=$runner;
$this->attachBehaviors($this->behaviors());
}
/**
* Initializes the command object.
* This method is invoked after a command object is created and initialized with configurations.
* You may override this method to further customize the command before it executes.
* @since 1.1.6
*/
public function init()
{
}
/**
* Returns a list of behaviors that this command should behave as.
* The return value should be an array of behavior configurations indexed by
* behavior names. Each behavior configuration can be either a string specifying
* the behavior class or an array of the following structure:
* <pre>
* 'behaviorName'=>array(
* 'class'=>'path.to.BehaviorClass',
* 'property1'=>'value1',
* 'property2'=>'value2',
* )
* </pre>
*
* Note, the behavior classes must implement {@link IBehavior} or extend from
* {@link CBehavior}. Behaviors declared in this method will be attached
* to the controller when it is instantiated.
*
* For more details about behaviors, see {@link CComponent}.
* @return array the behavior configurations (behavior name=>behavior configuration)
* @since 1.1.11
*/
public function behaviors()
{
return array();
}
/**
* Executes the command.
* The default implementation will parse the input parameters and
* dispatch the command request to an appropriate action with the corresponding
* option values
* @param array $args command line parameters for this command.
* @return integer application exit code, which is returned by the invoked action. 0 if the action did not return anything.
* (return value is available since version 1.1.11)
*/
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();
// named and unnamed options
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]);
}
// try global options
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;
}
/**
* This method is invoked right before an action is to be executed.
* You may override this method to do last-minute preparation for the action.
* @param string $action the action name
* @param array $params the parameters to be passed to the action method.
* @return boolean whether the action should be executed.
*/
protected function beforeAction($action,$params)
{
if($this->hasEventHandler('onBeforeAction'))
{
$event = new CConsoleCommandEvent($this,$params,$action);
$this->onBeforeAction($event);
return !$event->stopCommand;
}
else
{
return true;
}
}
/**
* This method is invoked right after an action finishes execution.
* You may override this method to do some postprocessing for the action.
* @param string $action the action name
* @param array $params the parameters to be passed to the action method.
* @param integer $exitCode the application exit code returned by the action method.
* @return integer application exit code (return value is available since version 1.1.11)
*/
protected function afterAction($action,$params,$exitCode=0)
{
$event=new CConsoleCommandEvent($this,$params,$action,$exitCode);
if($this->hasEventHandler('onAfterAction'))
$this->onAfterAction($event);
return $event->exitCode;
}
/**
* Parses the command line arguments and determines which action to perform.
* @param array $args command line arguments
* @return array the action name, named options (name=>value), and unnamed options
* @since 1.1.5
*/
protected function resolveRequest($args)
{
$options=array(); // named parameters
$params=array(); // unnamed parameters
foreach($args as $arg)
{
if(preg_match('/^--(\w+)(=(.*))?$/',$arg,$matches)) // an option
{
$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);
}
/**
* @return string the command name.
*/
public function getName()
{
return $this->_name;
}
/**
* @return CConsoleCommandRunner the command runner instance
*/
public function getCommandRunner()
{
return $this->_runner;
}
/**
* Provides the command description.
* This method may be overridden to return the actual command description.
* @return string the command description. Defaults to 'Usage: php entry-script.php command-name'.
*/
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;
}
/**
* Provides the command option help information.
* The default implementation will return all available actions together with their
* corresponding option information.
* @return array the command option help information. Each array element describes
* the help information for a single action.
* @since 1.1.5
*/
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;
}
/**
* Displays a usage error.
* This method will then terminate the execution of the current application.
* @param string $message the error message
*/
public function usageError($message)
{
echo "Error: $message\n\n".$this->getHelp()."\n";
exit(1);
}
/**
* Copies a list of files from one place to another.
* @param array $fileList the list of files to be copied (name=>spec).
* The array keys are names displayed during the copy process, and array values are specifications
* for files to be copied. Each array value must be an array of the following structure:
* <ul>
* <li>source: required, the full path of the file/directory to be copied from</li>
* <li>target: required, the full path of the file/directory to be copied to</li>
* <li>callback: optional, the callback to be invoked when copying a file. The callback function
* should be declared as follows:
* <pre>
* function foo($source,$params)
* </pre>
* where $source parameter is the source file path, and the content returned
* by the function will be saved into the target file.</li>
* <li>params: optional, the parameters to be passed to the callback</li>
* </ul>
* @see buildFileList
*/
public function copyFiles($fileList)
{
$overwriteAll=false;
foreach($fileList as $name=>$file)
{
$source=strtr($file['source'],'/\\',DIRECTORY_SEPARATOR);
$target=strtr($file['target'],'/\\',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);
}
}
/**
* Builds the file list of a directory.
* This method traverses through the specified directory and builds
* a list of files and subdirectories that the directory contains.
* The result of this function can be passed to {@link copyFiles}.
* @param string $sourceDir the source directory
* @param string $targetDir the target directory
* @param string $baseDir base directory
* @param array $ignoreFiles list of the names of files that should
* be ignored in list building process. Argument available since 1.1.11.
* @param array $renameMap hash array of file names that should be
* renamed. Example value: array('1.old.txt'=>'2.new.txt').
* Argument available since 1.1.11.
* @return array the file list (see {@link copyFiles})
*/
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;
}
/**
* Creates all parent directories if they do not exist.
* @param string $directory the directory to be checked
*/
public function ensureDirectory($directory)
{
if(!is_dir($directory))
{
$this->ensureDirectory(dirname($directory));
echo " mkdir ".strtr($directory,'\\','/')."\n";
mkdir($directory);
}
}
/**
* Renders a view file.
* @param string $_viewFile_ view file path
* @param array $_data_ optional data to be extracted as local view variables
* @param boolean $_return_ whether to return the rendering result instead of displaying it
* @return mixed the rendering result if required. Null otherwise.
*/
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_);
}
/**
* Converts a word to its plural form.
* @param string $name the word to be pluralized
* @return string the pluralized word
*/
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';
}
/**
* Reads input via the readline PHP extension if that's available, or fgets() if readline is not installed.
*
* @param string $message to echo out before waiting for user input
* @param string $default the default string to be returned when user does not write anything.
* Defaults to null, means that default string is disabled. This parameter is available since version 1.1.11.
* @return mixed line read as a string, or false if input has been closed
*
* @since 1.1.9
*/
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;
}
}
/**
* Asks user to confirm by typing y or n.
*
* @param string $message to echo out before waiting for user input
* @param boolean $default this value is returned if no selection is made. This parameter has been available since version 1.1.11.
* @return boolean whether user confirmed
*
* @since 1.1.9
*/
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);
}
/**
* This event is raised before an action is to be executed.
* @param CConsoleCommandEvent $event the event parameter
* @since 1.1.11
*/
public function onBeforeAction($event)
{
$this->raiseEvent('onBeforeAction',$event);
}
/**
* This event is raised after an action finishes execution.
* @param CConsoleCommandEvent $event the event parameter
* @since 1.1.11
*/
public function onAfterAction($event)
{
$this->raiseEvent('onAfterAction',$event);
}
}

View file

@ -0,0 +1,53 @@
<?php
/**
* CConsoleCommandBehavior class file.
*
* @author Evgeny Blinov <e.a.blinov@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008-2013 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
/**
* CConsoleCommandBehavior is a base class for behaviors that are attached to a console command component.
*
* @property CConsoleCommand $owner The owner model that this behavior is attached to.
*
* @author Evgeny Blinov <e.a.blinov@gmail.com>
* @package system.console
* @since 1.1.11
*/
class CConsoleCommandBehavior extends CBehavior
{
/**
* Declares events and the corresponding event handler methods.
* The default implementation returns 'onAfterConstruct', 'onBeforeValidate' and 'onAfterValidate' events and handlers.
* If you override this method, make sure you merge the parent result to the return value.
* @return array events (array keys) and the corresponding event handler methods (array values).
* @see CBehavior::events
*/
public function events()
{
return array(
'onBeforeAction' => 'beforeAction',
'onAfterAction' => 'afterAction'
);
}
/**
* Responds to {@link CConsoleCommand::onBeforeAction} event.
* Override this method and make it public if you want to handle the corresponding event of the {@link CBehavior::owner owner}.
* @param CConsoleCommandEvent $event event parameter
*/
protected function beforeAction($event)
{
}
/**
* Responds to {@link CConsoleCommand::onAfterAction} event.
* Override this method and make it public if you want to handle the corresponding event of the {@link CBehavior::owner owner}.
* @param CConsoleCommandEvent $event event parameter
*/
protected function afterAction($event)
{
}
}

View file

@ -0,0 +1,52 @@
<?php
/**
* CConsoleCommandEvent class file.
*
* @author Evgeny Blinov <e.a.blinov@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008-2013 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
/**
* CConsoleCommandEvent class.
*
* CConsoleCommandEvent represents the event parameters needed by events raised by a console command.
*
* @author Evgeny Blinov <e.a.blinov@gmail.com>
* @package system.console
* @since 1.1.11
*/
class CConsoleCommandEvent extends CEvent
{
/**
* @var string the action name
*/
public $action;
/**
* @var boolean whether the action should be executed.
* If this property is set true by the event handler, the console command action will quit after handling this event.
* If false, which is the default, the normal execution cycles will continue, including performing the action and calling
* {@link CConsoleCommand::afterAction}.
*/
public $stopCommand=false;
/**
* @var integer exit code of application.
* This property is available in {@link CConsoleCommand::onAfterAction} event and will be set to the exit code
* returned by the console command action. You can set it to change application exit code.
*/
public $exitCode;
/**
* Constructor.
* @param mixed $sender sender of the event
* @param string $params the parameters to be passed to the action method.
* @param string $action the action name
* @param integer $exitCode the application exit code
*/
public function __construct($sender=null,$params=null,$action=null,$exitCode=0){
parent::__construct($sender,$params);
$this->action=$action;
$this->exitCode=$exitCode;
}
}

View file

@ -0,0 +1,180 @@
<?php
/**
* CConsoleCommandRunner class file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008-2013 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
/**
* CConsoleCommandRunner manages commands and executes the requested command.
*
* @property string $scriptName The entry script name.
* @property CConsoleCommand $command The currently active command.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @package system.console
* @since 1.0
*/
class CConsoleCommandRunner extends CComponent
{
/**
* @var array list of all available commands (command name=>command configuration).
* Each command configuration can be either a string or an array.
* If the former, the string should be the class name or
* {@link YiiBase::getPathOfAlias class path alias} of the command.
* If the latter, the array must contain a 'class' element which specifies
* the command's class name or {@link YiiBase::getPathOfAlias class path alias}.
* The rest name-value pairs in the array are used to initialize
* the corresponding command properties. For example,
* <pre>
* array(
* 'email'=>array(
* 'class'=>'path.to.Mailer',
* 'interval'=>3600,
* ),
* 'log'=>'path.to.LoggerCommand',
* )
* </pre>
*/
public $commands=array();
private $_scriptName;
private $_command;
/**
* Executes the requested command.
* @param array $args list of user supplied parameters (including the entry script name and the command name).
* @return integer|null application exit code returned by the command.
* if null is returned, application will not exit explicitly. See also {@link CConsoleApplication::processRequest()}.
* (return value is available since version 1.1.11)
*/
public function run($args)
{
$this->_scriptName=$args[0];
array_shift($args);
if(isset($args[0]))
{
$name=$args[0];
array_shift($args);
}
else
$name='help';
$oldCommand=$this->_command;
if(($command=$this->createCommand($name))===null)
$command=$this->createCommand('help');
$this->_command=$command;
$command->init();
$exitCode=$command->run($args);
$this->_command=$oldCommand;
return $exitCode;
}
/**
* @return string the entry script name
*/
public function getScriptName()
{
return $this->_scriptName;
}
/**
* Returns the currently running command.
* @return CConsoleCommand|null the currently active command.
* @since 1.1.14
*/
public function getCommand()
{
return $this->_command;
}
/**
* @param CConsoleCommand $value the currently active command.
* @since 1.1.14
*/
public function setCommand($value)
{
$this->_command=$value;
}
/**
* Searches for commands under the specified directory.
* @param string $path the directory containing the command class files.
* @return array list of commands (command name=>command class file)
*/
public function findCommands($path)
{
if(($dir=@opendir($path))===false)
return array();
$commands=array();
while(($name=readdir($dir))!==false)
{
$file=$path.DIRECTORY_SEPARATOR.$name;
if(!strcasecmp(substr($name,-11),'Command.php') && is_file($file))
$commands[strtolower(substr($name,0,-11))]=$file;
}
closedir($dir);
return $commands;
}
/**
* Adds commands from the specified command path.
* If a command already exists, the new one will be ignored.
* @param string $path the alias of the directory containing the command class files.
*/
public function addCommands($path)
{
if(($commands=$this->findCommands($path))!==array())
{
foreach($commands as $name=>$file)
{
if(!isset($this->commands[$name]))
$this->commands[$name]=$file;
}
}
}
/**
* @param string $name command name (case-insensitive)
* @return CConsoleCommand the command object. Null if the name is invalid.
*/
public function createCommand($name)
{
$name=strtolower($name);
$command=null;
if(isset($this->commands[$name]))
$command=$this->commands[$name];
else
{
$commands=array_change_key_case($this->commands);
if(isset($commands[$name]))
$command=$commands[$name];
}
if($command!==null)
{
if(is_string($command)) // class file path or alias
{
if(strpos($command,'/')!==false || strpos($command,'\\')!==false)
{
$className=substr(basename($command),0,-4);
if(!class_exists($className,false))
require_once($command);
}
else // an alias
$className=Yii::import($command);
return new $className($name,$this);
}
else // an array configuration
return Yii::createComponent($command,$name,$this);
}
elseif($name==='help')
return new CHelpCommand('help',$this);
else
return null;
}
}

View file

@ -0,0 +1,76 @@
<?php
/**
* CHelpCommand class file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008-2013 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
/**
* CHelpCommand represents a console help command.
*
* CHelpCommand displays the available command list or the help instructions
* about a specific command.
*
* To use this command, enter the following on the command line:
* <pre>
* php path/to/entry_script.php help [command name]
* </pre>
* In the above, if the command name is not provided, it will display all
* available commands.
*
* @property string $help The command description.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @package system.console
* @since 1.0
*/
class CHelpCommand extends CConsoleCommand
{
/**
* Execute the action.
* @param array $args command line parameters specific for this command
* @return integer non zero application exit code after printing help
*/
public function run($args)
{
$runner=$this->getCommandRunner();
$commands=$runner->commands;
if(isset($args[0]))
$name=strtolower($args[0]);
if(!isset($args[0]) || !isset($commands[$name]))
{
if(!empty($commands))
{
echo "Yii command runner (based on Yii v".Yii::getVersion().")\n";
echo "Usage: ".$runner->getScriptName()." <command-name> [parameters...]\n";
echo "\nThe following commands are available:\n";
$commandNames=array_keys($commands);
sort($commandNames);
echo ' - '.implode("\n - ",$commandNames);
echo "\n\nTo see individual command help, use the following:\n";
echo " ".$runner->getScriptName()." help <command-name>\n";
}
else
{
echo "No available commands.\n";
echo "Please define them under the following directory:\n";
echo "\t".Yii::app()->getCommandPath()."\n";
}
}
else
echo $runner->createCommand($name)->getHelp();
return 1;
}
/**
* Provides the command description.
* @return string the command description.
*/
public function getHelp()
{
return parent::getHelp().' [command-name]';
}
}

View file

@ -0,0 +1,155 @@
<?php
/**
* CheckupCommand is a console command, to double check the site requirements :
* - directories rights
* - stored procedures
*
* To use this command, enter the following on the command line:
* <pre>
* php protected/yiic.php checkup
* </pre>
*
* @property string $help The command description.
*
*/
class CheckupCommand extends CConsoleCommand
{
protected $basePath;
/**
* Execute the action.
* @param array $args command line parameters specific for this command
* @return integer non zero application exit code after printing help
*/
public function run($args)
{
$runner=$this->getCommandRunner();
$commands=$runner->commands;
$root = realpath(Yii::app()->getBasePath().DIRECTORY_SEPARATOR.'..');
$this->basePath = str_replace(DIRECTORY_SEPARATOR, '/', $root);
if (isset($args[0])) {
echo "Yii checkup command\n";
echo "Usage: yiic checkup\n";
return 1;
} else {
self::checkDirectories();
//self::checkStoredProcedures();
self::checkModels();
echo "ok\n";
return 0;
}
}
/**
* Provides the command description.
* @return string the command description.
*/
public function getHelp()
{
return parent::getHelp().'checkup';
}
private function isDirWritable($dir)
{
if (!is_writable($dir)) {
echo "directory $dir is not writable!\n";
}
}
/**
* Vérifie les répertoires nécessitant le droit d'écriture
*/
public function checkDirectories()
{
$root = $this->basePath;
//self::isDirWritable("$root/protected/data/.");
self::isDirWritable("$root/yaamp/runtime/.");
}
/**
* Vérifie les procédures stockées
*/
private function callStoredProc($proc, $params=array())
{
$db = Yii::app()->db;
$params = implode(',', $params);
$command = $db->createCommand("CALL $proc($params);");
try {
$res = $command->execute();
$command->cancel();
} catch (CDbException $e) {
return $e->getMessage();
}
return true;
}
/**
* Vérifie les procédures stockées
*/
public function checkStoredProcedures()
{
$procs = array();
$procs['sp_test'] = array();
foreach ($procs as $name => $params) {
$res = self::callStoredProc($name, $params);
if ($res !== true) {
echo "$name: $res\n";
// TODO: execute this script automatically in dev.
// $sql = file_get_contents($this->basePath.'/protected/sql/DB_Procedures.sql');
}
}
}
/**
* Vérifie les modeles
*/
public function checkModels()
{
$modelsPath = $this->basePath.'/yaamp/models';
if(!is_dir($modelsPath))
echo "Directory $modelsPath is not a directory\n";
$db = Yii::app()->db;
$command = $db->createCommand("USE yaamp");
$command->execute();
$command->cancel();
$files = scandir($modelsPath);
foreach ($files as $model) {
if ($model=="." || $model=="..")
continue;
require_once($modelsPath.'/'.$model);
$table = pathinfo($model,PATHINFO_FILENAME);
$table = str_replace('Model','',$table);
$obj = CActiveRecord::model($table);
try{
$test = new $obj;
}catch (Exception $e){
echo "Error Model: $table \n";
echo $e->getMessage();
continue;
}
if ($test instanceof CActiveRecord){
$test->count();
//echo "count: $table"." - " .$test->count() ."\n";
}
}
}
}

82
web/yaamp/console.php Normal file
View file

@ -0,0 +1,82 @@
<?php
$_SERVER["HTTP_HOST"] = YAAMP_SITE_URL;
// required in PHP 5.4
date_default_timezone_set('Europe/Paris');
return array(
'name'=>YAAMP_SITE_URL,
'basePath'=>YAAMP_HTDOCS."/yaamp",
'preload'=>array('log'),
'import'=>array('application.components.*'),
'components'=>array(
'request' => array(
'hostInfo' => 'http://'.$_SERVER["HTTP_HOST"],
'baseUrl' => '',
),
// autoloading model and component classes
'import'=>array(
'application.components.*',
'application.commands.*',
//'application.commands.shell.*',
'application.models.*',
'application.extensions.*',
),
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName'=>false,
'appendParams'=>false,
),
'assetManager'=>array(
'basePath'=>YAAMP_HTDOCS."/assets"
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
'levels'=>'debug, trace, error, warning',
),
// array(
// 'class'=>'CProfileLogRoute',
// 'report'=>'summary',
// ),
),
),
'user'=>array(
'allowAutoLogin'=>true,
'loginUrl'=>array('site/login'),
),
'db'=>array(
'class'=>'CDbConnection',
'connectionString'=>"mysql:host=".YAAMP_DBHOST.";dbname=".YAAMP_DBNAME,
'username'=>YAAMP_DBUSER,
'password'=>YAAMP_DBPASSWORD,
'enableProfiling'=>false,
'charset'=>'utf8',
'schemaCachingDuration'=>3600,
),
),
);

4
web/yiic Executable file
View file

@ -0,0 +1,4 @@
#!/bin/bash
php yiic.php $*

31
web/yiic.php Normal file
View file

@ -0,0 +1,31 @@
<?php
if(php_sapi_name() != "cli") return;
require_once('serverconfig.php');
//require_once('yaamp/include.php');
require_once('yaamp/core/core.php');
require_once('yaamp/ui/lib/lib.php');
$config = require_once('yaamp/console.php');
// fix for fcgi
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
defined('YII_DEBUG') or define('YII_DEBUG',true);
require_once('framework-1.0.8'.'/yii.php');
if(isset($config))
{
$app=Yii::createConsoleApplication($config);
$app->commandRunner->addCommands(YII_PATH.'/cli/commands');
}
else
$app=Yii::createConsoleApplication(array('basePath'=>dirname(__FILE__).'/cli'));
$env=@getenv('YII_CONSOLE_COMMANDS');
if(!empty($env))
$app->commandRunner->addCommands($env);
$app->run();