ShellDispatcher.php 9.7 KB

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