ShellDispatcher.php 9.7 KB

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