ShellDispatcher.php 9.5 KB

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