4 * Command-line code generation utility to automate programmer chores.
6 * Shell dispatcher class
10 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
11 * Copyright 2005-2010, Cake Software Foundation, Inc.
13 * Licensed under The MIT License
14 * Redistributions of files must retain the above copyright notice.
16 * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
17 * @link http://cakephp.org CakePHP(tm) Project
19 * @subpackage cake.cake.console
20 * @since CakePHP(tm) v 1.2.0.5012
21 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
23 if (!defined('E_DEPRECATED')) {
24 define('E_DEPRECATED', 8192);
30 * @subpackage cake.cake.console
32 class ShellDispatcher
{
35 * Standard input stream.
43 * Standard output stream.
51 * Standard error stream.
59 * Contains command switches parsed from the command line.
64 var $params = array();
67 * Contains arguments parsed from the command line.
75 * The file name of the shell that was invoked.
83 * The class name of the shell that was invoked.
88 var $shellClass = null;
91 * The command called if public methods are available.
96 var $shellCommand = null;
99 * The path locations of shells.
104 var $shellPaths = array();
107 * The path to the current shell location.
112 var $shellPath = null;
115 * The name of the shell in camelized.
120 var $shellName = null;
125 * The execution of the script is stopped after dispatching the request with
126 * a status code of either 0 or 1 according to the result of the dispatch.
128 * @param array $args the argv
132 function ShellDispatcher($args = array()) {
135 $this->__initConstants();
136 $this->parseParams($args);
137 $this->_initEnvironment();
138 $this->__buildPaths();
139 $this->_stop($this->dispatch() === false ?
1 : 0);
143 * Defines core configuration.
147 function __initConstants() {
148 if (function_exists('ini_set')) {
149 ini_set('display_errors', '1');
150 ini_set('error_reporting', E_ALL
& ~E_DEPRECATED
);
151 ini_set('html_errors', false);
152 ini_set('implicit_flush', true);
153 ini_set('max_execution_time', 0);
156 if (!defined('CAKE_CORE_INCLUDE_PATH')) {
157 define('PHP5', (PHP_VERSION
>= 5));
158 define('DS', DIRECTORY_SEPARATOR
);
159 define('CAKE_CORE_INCLUDE_PATH', dirname(dirname(dirname(__FILE__
))));
160 define('CORE_PATH', CAKE_CORE_INCLUDE_PATH
. DS
);
161 define('DISABLE_DEFAULT_ERROR_HANDLING', false);
162 define('CAKEPHP_SHELL', true);
164 require_once(CORE_PATH
. 'cake' . DS
. 'basics.php');
168 * Defines current working environment.
172 function _initEnvironment() {
173 $this->stdin
= fopen('php://stdin', 'r');
174 $this->stdout
= fopen('php://stdout', 'w');
175 $this->stderr
= fopen('php://stderr', 'w');
177 if (!$this->__bootstrap()) {
178 $this->stderr("\nCakePHP Console: ");
179 $this->stderr("\nUnable to load Cake core:");
180 $this->stderr("\tMake sure " . DS
. 'cake' . DS
. 'libs exists in ' . CAKE_CORE_INCLUDE_PATH
);
184 if (!isset($this->args
[0]) ||
!isset($this->params
['working'])) {
185 $this->stderr("\nCakePHP Console: ");
186 $this->stderr('This file has been loaded incorrectly and cannot continue.');
187 $this->stderr('Please make sure that ' . DIRECTORY_SEPARATOR
. 'cake' . DIRECTORY_SEPARATOR
. 'console is in your system path,');
188 $this->stderr('and check the manual for the correct usage of this command.');
189 $this->stderr('(http://manual.cakephp.org/)');
193 if (basename(__FILE__
) != basename($this->args
[0])) {
194 $this->stderr("\nCakePHP Console: ");
195 $this->stderr('Warning: the dispatcher may have been loaded incorrectly, which could lead to unexpected results...');
196 if ($this->getInput('Continue anyway?', array('y', 'n'), 'y') == 'n') {
205 * Builds the shell paths.
210 function __buildPaths() {
212 if (!class_exists('Folder')) {
213 require LIBS
. 'folder.php';
215 $plugins = App
::objects('plugin', null, false);
216 foreach ((array)$plugins as $plugin) {
217 $pluginPath = App
::pluginPath($plugin);
218 $path = $pluginPath . 'vendors' . DS
. 'shells' . DS
;
219 if (file_exists($path)) {
224 $vendorPaths = array_values(App
::path('vendors'));
225 foreach ($vendorPaths as $vendorPath) {
226 $path = rtrim($vendorPath, DS
) . DS
. 'shells' . DS
;
227 if (file_exists($path)) {
232 $this->shellPaths
= array_values(array_unique(array_merge($paths, App
::path('shells'))));
236 * Initializes the environment and loads the Cake core.
238 * @return boolean Success.
241 function __bootstrap() {
243 define('ROOT', $this->params
['root']);
244 define('APP_DIR', $this->params
['app']);
245 define('APP_PATH', $this->params
['working'] . DS
);
246 define('WWW_ROOT', APP_PATH
. $this->params
['webroot'] . DS
);
247 if (!is_dir(ROOT
. DS
. APP_DIR
. DS
. 'tmp')) {
248 define('TMP', CORE_PATH
. 'cake' . DS
. 'console' . DS
. 'templates' . DS
. 'skel' . DS
. 'tmp' . DS
);
252 CORE_PATH
. 'cake' . DS
. 'config' . DS
. 'paths.php',
253 CORE_PATH
. 'cake' . DS
. 'libs' . DS
. 'object.php',
254 CORE_PATH
. 'cake' . DS
. 'libs' . DS
. 'inflector.php',
255 CORE_PATH
. 'cake' . DS
. 'libs' . DS
. 'configure.php',
256 CORE_PATH
. 'cake' . DS
. 'libs' . DS
. 'file.php',
257 CORE_PATH
. 'cake' . DS
. 'libs' . DS
. 'cache.php',
258 CORE_PATH
. 'cake' . DS
. 'libs' . DS
. 'string.php',
259 CORE_PATH
. 'cake' . DS
. 'libs' . DS
. 'class_registry.php',
260 CORE_PATH
. 'cake' . DS
. 'console' . DS
. 'error.php'
263 foreach ($includes as $inc) {
264 if (!require($inc)) {
265 $this->stderr("Failed to load Cake core file {$inc}");
270 Configure
::getInstance(file_exists(CONFIGS
. 'bootstrap.php'));
272 if (!file_exists(APP_PATH
. 'config' . DS
. 'core.php')) {
273 include_once CORE_PATH
. 'cake' . DS
. 'console' . DS
. 'templates' . DS
. 'skel' . DS
. 'config' . DS
. 'core.php';
287 if (empty($this->params
['noclear'])) {
297 * Dispatches a CLI request
302 function dispatch() {
303 $arg = $this->shiftArgs();
309 if ($arg == 'help') {
314 list($plugin, $shell) = pluginSplit($arg);
315 $this->shell
= $shell;
316 $this->shellName
= Inflector
::camelize($shell);
317 $this->shellClass
= $this->shellName
. 'Shell';
321 if (isset($this->args
[0])) {
322 $arg = $this->args
[0];
323 $this->shellCommand
= Inflector
::variable($arg);
326 $Shell = $this->_getShell($plugin);
329 $title = sprintf(__('Error: Class %s could not be loaded.', true), $this->shellClass
);
330 $this->stderr($title . "\n");
336 if (is_a($Shell, 'Shell')) {
337 $Shell->initialize();
340 foreach ($Shell->taskNames
as $task) {
341 if (is_a($Shell->{$task}, 'Shell')) {
342 $Shell->{$task}->initialize();
343 $Shell->{$task}->loadTasks();
347 $task = Inflector
::camelize($arg);
349 if (in_array($task, $Shell->taskNames
)) {
351 $Shell->{$task}->startup();
353 if (isset($this->args
[0]) && $this->args
[0] == 'help') {
354 if (method_exists($Shell->{$task}, 'help')) {
355 $Shell->{$task}->help();
361 return $Shell->{$task}->execute();
363 $methods = array_diff(get_class_methods('Shell'), array('help'));
365 $methods = array_diff(get_class_methods($Shell), $methods);
366 $added = in_array(strtolower($arg), array_map('strtolower', $methods));
367 $private = $arg[0] == '_' && method_exists($Shell, $arg);
373 return $Shell->{$arg}();
375 if (method_exists($Shell, 'main')) {
377 return $Shell->main();
381 $title = sprintf(__('Error: Unknown %1$s command %2$s.', true), $this->shellName
, $arg);
382 $message = sprintf(__('For usage try `cake %s help`', true), $this->shell
);
383 $this->stderr($title . "\n" . $message . "\n");
388 * Get shell to use, either plugin shell or application shell
390 * All paths in the shellPaths property are searched.
391 * shell, shellPath and shellClass properties are taken into account.
393 * @param string $plugin Optionally the name of a plugin
394 * @return mixed False if no shell could be found or an object on success
397 function _getShell($plugin = null) {
398 foreach ($this->shellPaths
as $path) {
399 $this->shellPath
= $path . $this->shell
. '.php';
400 $pluginShellPath = DS
. $plugin . DS
. 'vendors' . DS
. 'shells' . DS
;
402 if ((strpos($path, $pluginShellPath) !== false ||
!$plugin) && file_exists($this->shellPath
)) {
407 if (!isset($loaded)) {
411 if (!class_exists('Shell')) {
412 require CONSOLE_LIBS
. 'shell.php';
415 if (!class_exists($this->shellClass
)) {
416 require $this->shellPath
;
418 if (!class_exists($this->shellClass
)) {
421 $Shell = new $this->shellClass($this);
426 * Prompts the user for input, and returns it.
428 * @param string $prompt Prompt text.
429 * @param mixed $options Array or string of options.
430 * @param string $default Default input value.
431 * @return Either the default value, or the user-provided input.
434 function getInput($prompt, $options = null, $default = null) {
435 if (!is_array($options)) {
438 $printOptions = '(' . implode('/', $options) . ')';
441 if ($default === null) {
442 $this->stdout($prompt . " $printOptions \n" . '> ', false);
444 $this->stdout($prompt . " $printOptions \n" . "[$default] > ", false);
446 $result = fgets($this->stdin
);
448 if ($result === false) {
451 $result = trim($result);
453 if ($default != null && empty($result)) {
460 * Outputs to the stdout filehandle.
462 * @param string $string String to output.
463 * @param boolean $newline If true, the outputs gets an added newline.
464 * @return integer Returns the number of bytes output to stdout.
467 function stdout($string, $newline = true) {
469 return fwrite($this->stdout
, $string . "\n");
471 return fwrite($this->stdout
, $string);
476 * Outputs to the stderr filehandle.
478 * @param string $string Error text to output.
481 function stderr($string) {
482 fwrite($this->stderr
, $string);
486 * Parses command line options
488 * @param array $params Parameters to parse
491 function parseParams($params) {
492 $this->__parseParams($params);
493 $defaults = array('app' => 'app', 'root' => dirname(dirname(dirname(__FILE__
))), 'working' => null, 'webroot' => 'webroot');
494 $params = array_merge($defaults, array_intersect_key($this->params
, $defaults));
496 foreach ($defaults as $default => $value) {
497 if (strpos($params[$default], '\\') !== false) {
502 $params = str_replace('\\', '/', $params);
504 if (isset($params['working'])) {
505 $params['working'] = trim($params['working']);
507 if (!empty($params['working']) && (!isset($this->args
[0]) ||
isset($this->args
[0]) && $this->args
[0]{0} !== '.')) {
508 if (empty($this->params
['app']) && $params['working'] != $params['root']) {
509 $params['root'] = dirname($params['working']);
510 $params['app'] = basename($params['working']);
512 $params['root'] = $params['working'];
516 if ($params['app'][0] == '/' ||
preg_match('/([a-z])(:)/i', $params['app'], $matches)) {
517 $params['root'] = dirname($params['app']);
518 } elseif (strpos($params['app'], '/')) {
519 $params['root'] .= '/' . dirname($params['app']);
522 $params['app'] = basename($params['app']);
523 $params['working'] = rtrim($params['root'], '/');
524 if (!$isWin ||
!preg_match('/^[A-Z]:$/i', $params['app'])) {
525 $params['working'] .= '/' . $params['app'];
528 if (!empty($matches[0]) ||
!empty($isWin)) {
529 $params = str_replace('/', '\\', $params);
532 $this->params
= array_merge($this->params
, $params);
536 * Helper for recursively parsing params
538 * @return array params
541 function __parseParams($params) {
542 $count = count($params);
543 for ($i = 0; $i < $count; $i++
) {
544 if (isset($params[$i])) {
545 if ($params[$i]{0} === '-') {
546 $key = substr($params[$i], 1);
547 $this->params
[$key] = true;
549 if (isset($params[++
$i])) {
550 if ($params[$i]{0} !== '-') {
551 $this->params
[$key] = str_replace('"', '', $params[$i]);
555 $this->__parseParams($params);
559 $this->args
[] = $params[$i];
568 * Removes first argument and shifts other arguments up
570 * @return mixed Null if there are no arguments otherwise the shifted argument
573 function shiftArgs() {
574 return array_shift($this->args
);
584 $this->stdout("\nWelcome to CakePHP v" . Configure
::version() . " Console");
585 $this->stdout("---------------------------------------------------------------");
586 $this->stdout("Current Paths:");
587 $this->stdout(" -app: ". $this->params
['app']);
588 $this->stdout(" -working: " . rtrim($this->params
['working'], DS
));
589 $this->stdout(" -root: " . rtrim($this->params
['root'], DS
));
590 $this->stdout(" -core: " . rtrim(CORE_PATH
, DS
));
592 $this->stdout("Changing Paths:");
593 $this->stdout("your working path should be the same as your application path");
594 $this->stdout("to change your path use the '-app' param.");
595 $this->stdout("Example: -app relative/path/to/myapp or -app /absolute/path/to/myapp");
597 $this->stdout("\nAvailable Shells:");
598 $shellList = array();
599 foreach ($this->shellPaths
as $path) {
600 if (!is_dir($path)) {
603 $shells = App
::objects('file', $path);
604 if (empty($shells)) {
607 if (preg_match('@plugins[\\\/]([^\\\/]*)@', $path, $matches)) {
608 $type = Inflector
::camelize($matches[1]);
609 } elseif (preg_match('@([^\\\/]*)[\\\/]vendors[\\\/]@', $path, $matches)) {
611 } elseif (strpos($path, CAKE_CORE_INCLUDE_PATH
. DS
. 'cake') === 0) {
616 foreach ($shells as $shell) {
617 if ($shell !== 'shell.php') {
618 $shell = str_replace('.php', '', $shell);
619 $shellList[$shell][$type] = $type;
626 $width = exec('tput cols') - 2;
631 $columns = max(1, floor($width / 30));
632 $rows = ceil(count($shellList) / $columns);
634 foreach ($shellList as $shell => $types) {
636 $shellList[$shell] = str_pad($shell . ' [' . implode ($types, ', ') . ']', $width / $columns);
638 $out = array_chunk($shellList, $rows);
639 for ($i = 0; $i < $rows; $i++
) {
641 for ($j = 0; $j < $columns; $j++
) {
642 if (!isset($out[$j][$i])) {
645 $row .= $out[$j][$i];
647 $this->stdout(" " . $row);
650 $this->stdout("\nTo run a command, type 'cake shell_name [args]'");
651 $this->stdout("To get help on a specific command, type 'cake shell_name help'");
655 * Stop execution of the current script
657 * @param $status see http://php.net/exit for values
661 function _stop($status = 0) {
665 if (!defined('DISABLE_AUTO_DISPATCH')) {
666 $dispatcher = new ShellDispatcher($argv);