ShellDispatcher.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. /**
  3. * ShellDispatcher file
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake.console
  16. * @since CakePHP(tm) v 2.0
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. /**
  20. * Shell dispatcher handles dispatching cli commands.
  21. *
  22. * @package cake.console
  23. */
  24. class ShellDispatcher {
  25. /**
  26. * Contains command switches parsed from the command line.
  27. *
  28. * @var array
  29. * @access public
  30. */
  31. public $params = array();
  32. /**
  33. * Contains arguments parsed from the command line.
  34. *
  35. * @var array
  36. * @access public
  37. */
  38. public $args = array();
  39. /**
  40. * Constructor
  41. *
  42. * The execution of the script is stopped after dispatching the request with
  43. * a status code of either 0 or 1 according to the result of the dispatch.
  44. *
  45. * @param array $args the argv
  46. * @return void
  47. */
  48. public function __construct($args = array(), $bootstrap = true) {
  49. set_time_limit(0);
  50. if ($bootstrap) {
  51. $this->__initConstants();
  52. }
  53. $this->parseParams($args);
  54. if ($bootstrap) {
  55. $this->_initEnvironment();
  56. }
  57. }
  58. /**
  59. * Run the dispatcher
  60. *
  61. * @return void
  62. */
  63. public static function run($argv) {
  64. $dispatcher = new ShellDispatcher($argv);
  65. $dispatcher->_stop($dispatcher->dispatch() === false ? 1 : 0);
  66. }
  67. /**
  68. * Defines core configuration.
  69. *
  70. * @access private
  71. */
  72. function __initConstants() {
  73. if (function_exists('ini_set')) {
  74. ini_set('html_errors', false);
  75. ini_set('implicit_flush', true);
  76. ini_set('max_execution_time', 0);
  77. }
  78. if (!defined('CAKE_CORE_INCLUDE_PATH')) {
  79. define('DS', DIRECTORY_SEPARATOR);
  80. define('CAKE_CORE_INCLUDE_PATH', dirname(dirname(dirname(__FILE__))));
  81. define('CAKEPHP_SHELL', true);
  82. if (!defined('CORE_PATH')) {
  83. define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
  84. }
  85. }
  86. }
  87. /**
  88. * Defines current working environment.
  89. *
  90. */
  91. protected function _initEnvironment() {
  92. if (!$this->__bootstrap()) {
  93. $message = "Unable to load CakePHP core.\nMake sure " . DS . 'cake' . DS . 'libs exists in ' . CAKE_CORE_INCLUDE_PATH;
  94. throw new CakeException($message);
  95. }
  96. if (!isset($this->args[0]) || !isset($this->params['working'])) {
  97. $message = "This file has been loaded incorrectly and cannot continue.\n" .
  98. "Please make sure that " . DIRECTORY_SEPARATOR . "cake" . DIRECTORY_SEPARATOR . "console is in your system path,\n" .
  99. "and check the cookbook for the correct usage of this command.\n" .
  100. "(http://book.cakephp.org/)";
  101. throw new CakeException($message);
  102. }
  103. $this->shiftArgs();
  104. }
  105. /**
  106. * Initializes the environment and loads the Cake core.
  107. *
  108. * @return boolean Success.
  109. * @access private
  110. */
  111. function __bootstrap() {
  112. define('ROOT', $this->params['root']);
  113. define('APP_DIR', $this->params['app']);
  114. define('APP_PATH', $this->params['working'] . DS);
  115. define('WWW_ROOT', APP_PATH . $this->params['webroot'] . DS);
  116. if (!is_dir(ROOT . DS . APP_DIR . DS . 'tmp')) {
  117. define('TMP', CAKE_CORE_INCLUDE_PATH . DS . 'cake' . DS . 'console' . DS . 'templates' . DS . 'skel' . DS . 'tmp' . DS);
  118. }
  119. $boot = file_exists(ROOT . DS . APP_DIR . DS . 'config' . DS . 'bootstrap.php');
  120. require CORE_PATH . 'Cake' . DS . 'bootstrap.php';
  121. if (!file_exists(APP_PATH . 'config' . DS . 'core.php')) {
  122. include_once CAKE_CORE_INCLUDE_PATH . DS . 'cake' . DS . 'console' . DS . 'templates' . DS . 'skel' . DS . 'config' . DS . 'core.php';
  123. App::build();
  124. }
  125. require_once CONSOLE_LIBS . 'ConsoleErrorHandler.php';
  126. set_exception_handler(array('ConsoleErrorHandler', 'handleException'));
  127. set_error_handler(array('ConsoleErrorHandler', 'handleError'), Configure::read('Error.level'));
  128. if (!defined('FULL_BASE_URL')) {
  129. define('FULL_BASE_URL', '/');
  130. }
  131. return true;
  132. }
  133. /**
  134. * Dispatches a CLI request
  135. *
  136. * @return boolean
  137. */
  138. public function dispatch() {
  139. $shell = $this->shiftArgs();
  140. if (!$shell) {
  141. $this->help();
  142. return false;
  143. }
  144. if (in_array($shell, array('help', '--help', '-h'))) {
  145. $this->help();
  146. return true;
  147. }
  148. $Shell = $this->_getShell($shell);
  149. $command = null;
  150. if (isset($this->args[0])) {
  151. $command = $this->args[0];
  152. }
  153. if ($Shell instanceof Shell) {
  154. $Shell->initialize();
  155. $Shell->loadTasks();
  156. return $Shell->runCommand($command, $this->args);
  157. }
  158. $methods = array_diff(get_class_methods($Shell), get_class_methods('Shell'));
  159. $added = in_array($command, $methods);
  160. $private = $command[0] == '_' && method_exists($Shell, $command);
  161. if (!$private) {
  162. if ($added) {
  163. $this->shiftArgs();
  164. $Shell->startup();
  165. return $Shell->{$command}();
  166. }
  167. if (method_exists($Shell, 'main')) {
  168. $Shell->startup();
  169. return $Shell->main();
  170. }
  171. }
  172. throw new MissingShellMethodException(array('shell' => $shell, 'method' => $arg));
  173. }
  174. /**
  175. * Get shell to use, either plugin shell or application shell
  176. *
  177. * All paths in the loaded shell paths are searched.
  178. *
  179. * @param string $shell Optionally the name of a plugin
  180. * @return mixed False if no shell could be found or an object on success
  181. * @throws MissingShellFileException, MissingShellClassException when errors are encountered.
  182. */
  183. protected function _getShell($shell) {
  184. list($plugin, $shell) = pluginSplit($shell, true);
  185. $class = Inflector::camelize($shell) . 'Shell';
  186. App::uses('Shell', 'Console');
  187. App::uses($class, $plugin . 'Console/Command');
  188. if (!class_exists($class)) {
  189. throw new MissingShellFileException(array('shell' => $shell));
  190. }
  191. $Shell = new $class();
  192. return $Shell;
  193. }
  194. /**
  195. * Parses command line options and extracts the directory paths from $params
  196. *
  197. * @param array $params Parameters to parse
  198. */
  199. public function parseParams($args) {
  200. $this->_parsePaths($args);
  201. $defaults = array(
  202. 'app' => 'app',
  203. 'root' => dirname(dirname(dirname(__FILE__))),
  204. 'working' => null,
  205. 'webroot' => 'webroot'
  206. );
  207. $params = array_merge($defaults, array_intersect_key($this->params, $defaults));
  208. $isWin = false;
  209. foreach ($defaults as $default => $value) {
  210. if (strpos($params[$default], '\\') !== false) {
  211. $isWin = true;
  212. break;
  213. }
  214. }
  215. $params = str_replace('\\', '/', $params);
  216. if (isset($params['working'])) {
  217. $params['working'] = trim($params['working']);
  218. }
  219. if (!empty($params['working']) && (!isset($this->args[0]) || isset($this->args[0]) && $this->args[0]{0} !== '.')) {
  220. if (empty($this->params['app']) && $params['working'] != $params['root']) {
  221. $params['root'] = dirname($params['working']);
  222. $params['app'] = basename($params['working']);
  223. } else {
  224. $params['root'] = $params['working'];
  225. }
  226. }
  227. if ($params['app'][0] == '/' || preg_match('/([a-z])(:)/i', $params['app'], $matches)) {
  228. $params['root'] = dirname($params['app']);
  229. } elseif (strpos($params['app'], '/')) {
  230. $params['root'] .= '/' . dirname($params['app']);
  231. }
  232. $params['app'] = basename($params['app']);
  233. $params['working'] = rtrim($params['root'], '/');
  234. if (!$isWin || !preg_match('/^[A-Z]:$/i', $params['app'])) {
  235. $params['working'] .= '/' . $params['app'];
  236. }
  237. if (!empty($matches[0]) || !empty($isWin)) {
  238. $params = str_replace('/', '\\', $params);
  239. }
  240. $this->params = array_merge($this->params, $params);
  241. }
  242. /**
  243. * Parses out the paths from from the argv
  244. *
  245. * @return void
  246. */
  247. protected function _parsePaths($args) {
  248. $parsed = array();
  249. $keys = array('-working', '--working', '-app', '--app', '-root', '--root');
  250. foreach ($keys as $key) {
  251. $index = array_search($key, $args);
  252. if ($index !== false) {
  253. $keyname = str_replace('-', '', $key);
  254. $valueIndex = $index + 1;
  255. $parsed[$keyname] = $args[$valueIndex];
  256. array_splice($args, $index, 2);
  257. }
  258. }
  259. $this->args = $args;
  260. $this->params = $parsed;
  261. }
  262. /**
  263. * Removes first argument and shifts other arguments up
  264. *
  265. * @return mixed Null if there are no arguments otherwise the shifted argument
  266. */
  267. public function shiftArgs() {
  268. return array_shift($this->args);
  269. }
  270. /**
  271. * Shows console help. Performs an internal dispatch to the CommandList Shell
  272. *
  273. */
  274. public function help() {
  275. $this->args = array_merge(array('command_list'), $this->args);
  276. $this->dispatch();
  277. }
  278. /**
  279. * Stop execution of the current script
  280. *
  281. * @param $status see http://php.net/exit for values
  282. * @return void
  283. */
  284. protected function _stop($status = 0) {
  285. exit($status);
  286. }
  287. }