ShellDispatcher.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. try {
  154. if ($Shell instanceof Shell) {
  155. $Shell->initialize();
  156. $Shell->loadTasks();
  157. return $Shell->runCommand($command, $this->args);
  158. }
  159. $methods = array_diff(get_class_methods($Shell), get_class_methods('Shell'));
  160. $added = in_array($command, $methods);
  161. $private = $command[0] == '_' && method_exists($Shell, $command);
  162. if (!$private) {
  163. if ($added) {
  164. $this->shiftArgs();
  165. $Shell->startup();
  166. return $Shell->{$command}();
  167. }
  168. if (method_exists($Shell, 'main')) {
  169. $Shell->startup();
  170. return $Shell->main();
  171. }
  172. }
  173. } catch(ConsoleException $e) {
  174. $this->help();
  175. $this->_stop(1);
  176. }
  177. throw new MissingShellMethodException(array('shell' => $shell, 'method' => $arg));
  178. }
  179. /**
  180. * Get shell to use, either plugin shell or application shell
  181. *
  182. * All paths in the loaded shell paths are searched.
  183. *
  184. * @param string $shell Optionally the name of a plugin
  185. * @return mixed False if no shell could be found or an object on success
  186. * @throws MissingShellFileException, MissingShellClassException when errors are encountered.
  187. */
  188. protected function _getShell($shell) {
  189. list($plugin, $shell) = pluginSplit($shell, true);
  190. $class = Inflector::camelize($shell) . 'Shell';
  191. App::uses('Shell', 'Console');
  192. App::uses($class, $plugin . 'Console/Command');
  193. if (!class_exists($class)) {
  194. throw new MissingShellFileException(array('shell' => $shell));
  195. }
  196. $Shell = new $class();
  197. return $Shell;
  198. }
  199. /**
  200. * Parses command line options and extracts the directory paths from $params
  201. *
  202. * @param array $params Parameters to parse
  203. */
  204. public function parseParams($args) {
  205. $this->_parsePaths($args);
  206. $defaults = array(
  207. 'app' => 'app',
  208. 'root' => dirname(dirname(dirname(dirname(__FILE__)))),
  209. 'working' => null,
  210. 'webroot' => 'webroot'
  211. );
  212. $params = array_merge($defaults, array_intersect_key($this->params, $defaults));
  213. $isWin = false;
  214. foreach ($defaults as $default => $value) {
  215. if (strpos($params[$default], '\\') !== false) {
  216. $isWin = true;
  217. break;
  218. }
  219. }
  220. $params = str_replace('\\', '/', $params);
  221. if (isset($params['working'])) {
  222. $params['working'] = trim($params['working']);
  223. }
  224. if (!empty($params['working']) && (!isset($this->args[0]) || isset($this->args[0]) && $this->args[0]{0} !== '.')) {
  225. if (empty($this->params['app']) && $params['working'] != $params['root']) {
  226. $params['root'] = dirname($params['working']);
  227. $params['app'] = basename($params['working']);
  228. } else {
  229. $params['root'] = $params['working'];
  230. }
  231. }
  232. if ($params['app'][0] == '/' || preg_match('/([a-z])(:)/i', $params['app'], $matches)) {
  233. $params['root'] = dirname($params['app']);
  234. } elseif (strpos($params['app'], '/')) {
  235. $params['root'] .= '/' . dirname($params['app']);
  236. }
  237. $params['app'] = basename($params['app']);
  238. $params['working'] = rtrim($params['root'], '/');
  239. if (!$isWin || !preg_match('/^[A-Z]:$/i', $params['app'])) {
  240. $params['working'] .= '/' . $params['app'];
  241. }
  242. if (!empty($matches[0]) || !empty($isWin)) {
  243. $params = str_replace('/', '\\', $params);
  244. }
  245. $this->params = array_merge($this->params, $params);
  246. }
  247. /**
  248. * Parses out the paths from from the argv
  249. *
  250. * @return void
  251. */
  252. protected function _parsePaths($args) {
  253. $parsed = array();
  254. $keys = array('-working', '--working', '-app', '--app', '-root', '--root');
  255. foreach ($keys as $key) {
  256. $index = array_search($key, $args);
  257. if ($index !== false) {
  258. $keyname = str_replace('-', '', $key);
  259. $valueIndex = $index + 1;
  260. $parsed[$keyname] = $args[$valueIndex];
  261. array_splice($args, $index, 2);
  262. }
  263. }
  264. $this->args = $args;
  265. $this->params = $parsed;
  266. }
  267. /**
  268. * Removes first argument and shifts other arguments up
  269. *
  270. * @return mixed Null if there are no arguments otherwise the shifted argument
  271. */
  272. public function shiftArgs() {
  273. return array_shift($this->args);
  274. }
  275. /**
  276. * Shows console help. Performs an internal dispatch to the CommandList Shell
  277. *
  278. */
  279. public function help() {
  280. $this->args = array_merge(array('command_list'), $this->args);
  281. $this->dispatch();
  282. }
  283. /**
  284. * Stop execution of the current script
  285. *
  286. * @param $status see http://php.net/exit for values
  287. * @return void
  288. */
  289. protected function _stop($status = 0) {
  290. exit($status);
  291. }
  292. }