shell.php

Go to the documentation of this file.
00001 <?php
00002 /* SVN FILE: $Id: shell.php 8260 2009-07-28 20:01:42Z DarkAngelBGE $ */
00003 /**
00004  * Base class for Shells
00005  *
00006  * Long description for file
00007  *
00008  * PHP versions 4 and 5
00009  *
00010  * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
00011  * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
00012  *
00013  * Licensed under The MIT License
00014  * Redistributions of files must retain the above copyright notice.
00015  *
00016  * @filesource
00017  * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
00018  * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
00019  * @package       cake
00020  * @subpackage    cake.cake.console.libs
00021  * @since         CakePHP(tm) v 1.2.0.5012
00022  * @version       $Revision: 8260 $
00023  * @modifiedby    $LastChangedBy: DarkAngelBGE $
00024  * @lastmodified  $Date: 2009-07-28 16:01:42 -0400 (Tue, 28 Jul 2009) $
00025  * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
00026  */
00027 /**
00028  * Base class for command-line utilities for automating programmer chores.
00029  *
00030  * @package       cake
00031  * @subpackage    cake.cake.console.libs
00032  */
00033 class Shell extends Object {
00034 /**
00035  * An instance of the ShellDispatcher object that loaded this script
00036  *
00037  * @var ShellDispatcher
00038  * @access public
00039  */
00040     var $Dispatch = null;
00041 /**
00042  * If true, the script will ask for permission to perform actions.
00043  *
00044  * @var boolean
00045  * @access public
00046  */
00047     var $interactive = true;
00048 /**
00049  * Holds the DATABASE_CONFIG object for the app. Null if database.php could not be found,
00050  * or the app does not exist.
00051  *
00052  * @var DATABASE_CONFIG
00053  * @access public
00054  */
00055     var $DbConfig = null;
00056 /**
00057  * Contains command switches parsed from the command line.
00058  *
00059  * @var array
00060  * @access public
00061  */
00062     var $params = array();
00063 /**
00064  * Contains arguments parsed from the command line.
00065  *
00066  * @var array
00067  * @access public
00068  */
00069     var $args = array();
00070 /**
00071  * The file name of the shell that was invoked.
00072  *
00073  * @var string
00074  * @access public
00075  */
00076     var $shell = null;
00077 /**
00078  * The class name of the shell that was invoked.
00079  *
00080  * @var string
00081  * @access public
00082  */
00083     var $className = null;
00084 /**
00085  * The command called if public methods are available.
00086  *
00087  * @var string
00088  * @access public
00089  */
00090     var $command = null;
00091 /**
00092  * The name of the shell in camelized.
00093  *
00094  * @var string
00095  * @access public
00096  */
00097     var $name = null;
00098 /**
00099  * An alias for the shell
00100  *
00101  * @var string
00102  * @access public
00103  */
00104     var $alias = null;
00105 /**
00106  * Contains tasks to load and instantiate
00107  *
00108  * @var array
00109  * @access public
00110  */
00111     var $tasks = array();
00112 /**
00113  * Contains the loaded tasks
00114  *
00115  * @var array
00116  * @access public
00117  */
00118     var $taskNames = array();
00119 /**
00120  * Contains models to load and instantiate
00121  *
00122  * @var array
00123  * @access public
00124  */
00125     var $uses = array();
00126 /**
00127  *  Constructs this Shell instance.
00128  *
00129  */
00130     function __construct(&$dispatch) {
00131         $vars = array('params', 'args', 'shell', 'shellCommand' => 'command');
00132         foreach ($vars as $key => $var) {
00133             if (is_string($key)) {
00134                 $this->{$var} =& $dispatch->{$key};
00135             } else {
00136                 $this->{$var} =& $dispatch->{$var};
00137             }
00138         }
00139 
00140         if ($this->name == null) {
00141             $this->name = get_class($this);
00142         }
00143 
00144         if ($this->alias == null) {
00145             $this->alias = $this->name;
00146         }
00147 
00148         ClassRegistry::addObject($this->name, $this);
00149         ClassRegistry::map($this->name, $this->alias);
00150 
00151         if (!PHP5 && isset($this->args[0])) {
00152             if (strpos($this->name, strtolower(Inflector::camelize($this->args[0]))) !== false) {
00153                 $dispatch->shiftArgs();
00154             }
00155             if (strtolower($this->command) == strtolower(Inflector::variable($this->args[0])) && method_exists($this, $this->command)) {
00156                 $dispatch->shiftArgs();
00157             }
00158         }
00159 
00160         $this->Dispatch =& $dispatch;
00161     }
00162 /**
00163  * Initializes the Shell
00164  * acts as constructor for subclasses
00165  * allows configuration of tasks prior to shell execution
00166  *
00167  * @access public
00168  */
00169     function initialize() {
00170         $this->_loadModels();
00171     }
00172 /**
00173  * Starts up the the Shell
00174  * allows for checking and configuring prior to command or main execution
00175  * can be overriden in subclasses
00176  *
00177  * @access public
00178  */
00179     function startup() {
00180         $this->_welcome();
00181     }
00182 /**
00183  * Displays a header for the shell
00184  *
00185  * @access protected
00186  */
00187     function _welcome() {
00188         $this->out("\nWelcome to CakePHP v" . Configure::version() . " Console");
00189         $this->out("---------------------------------------------------------------");
00190         $this->out('App : '. $this->params['app']);
00191         $this->out('Path: '. $this->params['working']);
00192         $this->hr();
00193     }
00194 /**
00195  * Loads database file and constructs DATABASE_CONFIG class
00196  * makes $this->DbConfig available to subclasses
00197  *
00198  * @return bool
00199  * @access protected
00200  */
00201     function _loadDbConfig() {
00202         if (config('database') && class_exists('DATABASE_CONFIG')) {
00203             $this->DbConfig =& new DATABASE_CONFIG();
00204             return true;
00205         }
00206         $this->err('Database config could not be loaded');
00207         $this->out('Run \'bake\' to create the database configuration');
00208         return false;
00209     }
00210 /**
00211  * if var $uses = true
00212  * Loads AppModel file and constructs AppModel class
00213  * makes $this->AppModel available to subclasses
00214  * if var $uses is an array of models will load those models
00215  *
00216  * @return bool
00217  * @access protected
00218  */
00219     function _loadModels() {
00220         if ($this->uses === null || $this->uses === false) {
00221             return;
00222         }
00223 
00224         if ($this->uses === true && App::import('Model', 'AppModel')) {
00225             $this->AppModel =& new AppModel(false, false, false);
00226             return true;
00227         }
00228 
00229         if ($this->uses !== true && !empty($this->uses)) {
00230             $uses = is_array($this->uses) ? $this->uses : array($this->uses);
00231 
00232             $modelClassName = $uses[0];
00233             if (strpos($uses[0], '.') !== false) {
00234                 list($plugin, $modelClassName) = explode('.', $uses[0]);
00235             }
00236             $this->modelClass = $modelClassName;
00237 
00238             foreach ($uses as $modelClass) {
00239                 $plugin = null;
00240                 if (strpos($modelClass, '.') !== false) {
00241                     list($plugin, $modelClass) = explode('.', $modelClass);
00242                     $plugin = $plugin . '.';
00243                 }
00244                 if (PHP5) {
00245                     $this->{$modelClass} = ClassRegistry::init($plugin . $modelClass);
00246                 } else {
00247                     $this->{$modelClass} =& ClassRegistry::init($plugin . $modelClass);
00248                 }
00249             }
00250             return true;
00251         }
00252         return false;
00253     }
00254 /**
00255  * Loads tasks defined in var $tasks
00256  *
00257  * @return bool
00258  * @access public
00259  */
00260     function loadTasks() {
00261         if ($this->tasks === null || $this->tasks === false || $this->tasks === true || empty($this->tasks)) {
00262             return true;
00263         }
00264 
00265         $tasks = $this->tasks;
00266         if (!is_array($tasks)) {
00267             $tasks = array($tasks);
00268         }
00269 
00270         foreach ($tasks as $taskName) {
00271             $task = Inflector::underscore($taskName);
00272             $taskClass = Inflector::camelize($taskName . 'Task');
00273 
00274             if (!class_exists($taskClass)) {
00275                 foreach ($this->Dispatch->shellPaths as $path) {
00276                     $taskPath = $path . 'tasks' . DS . $task.'.php';
00277                     if (file_exists($taskPath)) {
00278                         require_once $taskPath;
00279                         break;
00280                     }
00281                 }
00282             }
00283             if (ClassRegistry::isKeySet($taskClass)) {
00284                 $this->taskNames[] = $taskName;
00285                 if (!PHP5) {
00286                     $this->{$taskName} =& ClassRegistry::getObject($taskClass);
00287                 } else {
00288                     $this->{$taskName} = ClassRegistry::getObject($taskClass);
00289                 }
00290             } else {
00291                 $this->taskNames[] = $taskName;
00292                 if (!PHP5) {
00293                     $this->{$taskName} =& new $taskClass($this->Dispatch);
00294                 } else {
00295                     $this->{$taskName} = new $taskClass($this->Dispatch);
00296                 }
00297             }
00298 
00299             if (!isset($this->{$taskName})) {
00300                 $this->err("Task '" . $taskName . "' could not be loaded");
00301                 $this->_stop();
00302             }
00303         }
00304 
00305         return true;
00306     }
00307 /**
00308  * Prompts the user for input, and returns it.
00309  *
00310  * @param string $prompt Prompt text.
00311  * @param mixed $options Array or string of options.
00312  * @param string $default Default input value.
00313  * @return Either the default value, or the user-provided input.
00314  * @access public
00315  */
00316     function in($prompt, $options = null, $default = null) {
00317         if (!$this->interactive) {
00318             return $default;
00319         }
00320         $in = $this->Dispatch->getInput($prompt, $options, $default);
00321 
00322         if ($options && is_string($options)) {
00323             if (strpos($options, ',')) {
00324                 $options = explode(',', $options);
00325             } elseif (strpos($options, '/')) {
00326                 $options = explode('/', $options);
00327             } else {
00328                 $options = array($options);
00329             }
00330         }
00331         if (is_array($options)) {
00332             while ($in == '' || ($in && (!in_array(strtolower($in), $options) && !in_array(strtoupper($in), $options)) && !in_array($in, $options))) {
00333                 $in = $this->Dispatch->getInput($prompt, $options, $default);
00334             }
00335         }
00336         if ($in) {
00337             return $in;
00338         }
00339     }
00340 /**
00341  * Outputs to the stdout filehandle.
00342  *
00343  * @param string $string String to output.
00344  * @param boolean $newline If true, the outputs gets an added newline.
00345  * @access public
00346  */
00347     function out($string, $newline = true) {
00348         if (is_array($string)) {
00349             $str = '';
00350             foreach ($string as $message) {
00351                 $str .= $message ."\n";
00352             }
00353             $string = $str;
00354         }
00355         return $this->Dispatch->stdout($string, $newline);
00356     }
00357 /**
00358  * Outputs to the stderr filehandle.
00359  *
00360  * @param string $string Error text to output.
00361  * @access public
00362  */
00363     function err($string) {
00364         if (is_array($string)) {
00365             $str = '';
00366             foreach ($string as $message) {
00367                 $str .= $message ."\n";
00368             }
00369             $string = $str;
00370         }
00371         return $this->Dispatch->stderr($string."\n");
00372     }
00373 /**
00374  * Outputs a series of minus characters to the standard output, acts as a visual separator.
00375  *
00376  * @param boolean $newline If true, the outputs gets an added newline.
00377  * @access public
00378  */
00379     function hr($newline = false) {
00380         if ($newline) {
00381             $this->out("\n");
00382         }
00383         $this->out('---------------------------------------------------------------');
00384         if ($newline) {
00385             $this->out("\n");
00386         }
00387     }
00388 /**
00389  * Displays a formatted error message and exits the application
00390  *
00391  * @param string $title Title of the error message
00392  * @param string $msg Error message
00393  * @access public
00394  */
00395     function error($title, $msg) {
00396         $out  = "$title\n";
00397         $out .= "$msg\n";
00398         $out .= "\n";
00399         $this->err($out);
00400         $this->_stop();
00401     }
00402 /**
00403  * Will check the number args matches otherwise throw an error
00404  *
00405  * @param integer $expectedNum Expected number of paramters
00406  * @param string $command Command
00407  * @access protected
00408  */
00409     function _checkArgs($expectedNum, $command = null) {
00410         if (!$command) {
00411             $command = $this->command;
00412         }
00413         if (count($this->args) < $expectedNum) {
00414             $this->error("Wrong number of parameters: ".count($this->args), "Expected: {$expectedNum}\nPlease type 'cake {$this->shell} help' for help on usage of the {$this->name} {$command}");
00415         }
00416     }
00417 /**
00418  * Creates a file at given path
00419  *
00420  * @param string $path Where to put the file.
00421  * @param string $contents Content to put in the file.
00422  * @return boolean Success
00423  * @access public
00424  */
00425     function createFile ($path, $contents) {
00426         $path = str_replace(DS . DS, DS, $path);
00427         $this->out("\n" . sprintf(__("Creating file %s", true), $path));
00428         if (is_file($path) && $this->interactive === true) {
00429             $key = $this->in(__("File exists, overwrite?", true). " {$path}",  array('y', 'n', 'q'), 'n');
00430             if (strtolower($key) == 'q') {
00431                 $this->out(__("Quitting.", true) ."\n");
00432                 exit;
00433             } elseif (strtolower($key) != 'y') {
00434                 $this->out(__("Skip", true) ." {$path}\n");
00435                 return false;
00436             }
00437         }
00438         if (!class_exists('File')) {
00439             uses('file');
00440         }
00441 
00442         if ($File = new File($path, true)) {
00443             $data = $File->prepare($contents);
00444             $File->write($data);
00445             $this->out(__("Wrote", true) ." {$path}");
00446             return true;
00447         } else {
00448             $this->err(__("Error! Could not write to", true)." {$path}.\n");
00449             return false;
00450         }
00451     }
00452 /**
00453  * Outputs usage text on the standard output. Implement it in subclasses.
00454  *
00455  * @access public
00456  */
00457     function help() {
00458         if ($this->command != null) {
00459             $this->err("Unknown {$this->name} command '$this->command'.\nFor usage, try 'cake {$this->shell} help'.\n\n");
00460         } else {
00461             $this->Dispatch->help();
00462         }
00463     }
00464 /**
00465  * Action to create a Unit Test
00466  *
00467  * @return boolean Success
00468  * @access protected
00469  */
00470     function _checkUnitTest() {
00471         if (App::import('vendor', 'simpletest' . DS . 'simpletest')) {
00472             return true;
00473         }
00474         $unitTest = $this->in('SimpleTest is not installed.  Do you want to bake unit test files anyway?', array('y','n'), 'y');
00475         $result = strtolower($unitTest) == 'y' || strtolower($unitTest) == 'yes';
00476 
00477         if ($result) {
00478             $this->out("\nYou can download SimpleTest from http://simpletest.org", true);
00479         }
00480         return $result;
00481     }
00482 /**
00483  * Makes absolute file path easier to read
00484  *
00485  * @param string $file Absolute file path
00486  * @return sting short path
00487  * @access public
00488  */
00489     function shortPath($file) {
00490         $shortPath = str_replace(ROOT, null, $file);
00491         $shortPath = str_replace('..' . DS, '', $shortPath);
00492         return str_replace(DS . DS, DS, $shortPath);
00493     }
00494 /**
00495  * Checks for Configure::read('Routing.admin') and forces user to input it if not enabled
00496  *
00497  * @return string Admin route to use
00498  * @access public
00499  */
00500     function getAdmin() {
00501         $admin = '';
00502         $cakeAdmin = null;
00503         $adminRoute = Configure::read('Routing.admin');
00504         if (!empty($adminRoute)) {
00505             $cakeAdmin = $adminRoute . '_';
00506         } else {
00507             $this->out('You need to enable Configure::write(\'Routing.admin\',\'admin\') in /app/config/core.php to use admin routing.');
00508             $this->out('What would you like the admin route to be?');
00509             $this->out('Example: www.example.com/admin/controller');
00510             while ($admin == '') {
00511                 $admin = $this->in("What would you like the admin route to be?", null, 'admin');
00512             }
00513             if ($this->Project->cakeAdmin($admin) !== true) {
00514                 $this->out('Unable to write to /app/config/core.php.');
00515                 $this->out('You need to enable Configure::write(\'Routing.admin\',\'admin\') in /app/config/core.php to use admin routing.');
00516                 $this->_stop();
00517             } else {
00518                 $cakeAdmin = $admin . '_';
00519             }
00520         }
00521         return $cakeAdmin;
00522     }
00523 /**
00524  * Creates the proper controller path for the specified controller class name
00525  *
00526  * @param string $name Controller class name
00527  * @return string Path to controller
00528  * @access protected
00529  */
00530     function _controllerPath($name) {
00531         return strtolower(Inflector::underscore($name));
00532     }
00533 /**
00534  * Creates the proper controller plural name for the specified controller class name
00535  *
00536  * @param string $name Controller class name
00537  * @return string Controller plural name
00538  * @access protected
00539  */
00540     function _controllerName($name) {
00541         return Inflector::pluralize(Inflector::camelize($name));
00542     }
00543 /**
00544  * Creates the proper controller camelized name (singularized) for the specified name
00545  *
00546  * @param string $name Name
00547  * @return string Camelized and singularized controller name
00548  * @access protected
00549  */
00550     function _modelName($name) {
00551         return Inflector::camelize(Inflector::singularize($name));
00552     }
00553 /**
00554  * Creates the proper singular model key for associations
00555  *
00556  * @param string $name Controller class name
00557  * @return string Singular model key
00558  * @access protected
00559  */
00560     function _modelKey($name) {
00561         return Inflector::underscore(Inflector::singularize($name)).'_id';
00562     }
00563 /**
00564  * Creates the proper model name from a foreign key
00565  *
00566  * @param string $key Foreign key
00567  * @return string Model name
00568  * @access protected
00569  */
00570     function _modelNameFromKey($key) {
00571         $name = str_replace('_id', '',$key);
00572         return Inflector::camelize($name);
00573     }
00574 /**
00575  * creates the singular name for use in views.
00576  *
00577  * @param string $name
00578  * @return string $name
00579  * @access protected
00580  */
00581     function _singularName($name) {
00582         return Inflector::variable(Inflector::singularize($name));
00583     }
00584 /**
00585  * Creates the plural name for views
00586  *
00587  * @param string $name Name to use
00588  * @return string Plural name for views
00589  * @access protected
00590  */
00591     function _pluralName($name) {
00592         return Inflector::variable(Inflector::pluralize($name));
00593     }
00594 /**
00595  * Creates the singular human name used in views
00596  *
00597  * @param string $name Controller name
00598  * @return string Singular human name
00599  * @access protected
00600  */
00601     function _singularHumanName($name) {
00602         return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
00603     }
00604 /**
00605  * Creates the plural human name used in views
00606  *
00607  * @param string $name Controller name
00608  * @return string Plural human name
00609  * @access protected
00610  */
00611     function _pluralHumanName($name) {
00612         return Inflector::humanize(Inflector::underscore(Inflector::pluralize($name)));
00613     }
00614 }
00615 ?>

Generated on Sun Nov 22 00:30:51 2009 for CakePHP 1.2.x.x (v1.2.4.8284) by doxygen 1.4.7