ShellDispatcher.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. /**
  3. * ShellDispatcher file
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, 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-2011, 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. if ($bootstrap) {
  48. $this->_initConstants();
  49. }
  50. $this->parseParams($args);
  51. if ($bootstrap) {
  52. $this->_initEnvironment();
  53. }
  54. }
  55. /**
  56. * Run the dispatcher
  57. *
  58. * @param array $argv The argv from PHP
  59. * @return void
  60. */
  61. public static function run($argv) {
  62. $dispatcher = new ShellDispatcher($argv);
  63. $dispatcher->_stop($dispatcher->dispatch() === false ? 1 : 0);
  64. }
  65. /**
  66. * Defines core configuration.
  67. *
  68. * @return void
  69. */
  70. protected function _initConstants() {
  71. if (function_exists('ini_set')) {
  72. ini_set('html_errors', false);
  73. ini_set('implicit_flush', true);
  74. ini_set('max_execution_time', 0);
  75. }
  76. if (!defined('CAKE_CORE_INCLUDE_PATH')) {
  77. define('DS', DIRECTORY_SEPARATOR);
  78. define('CAKE_CORE_INCLUDE_PATH', dirname(dirname(dirname(__FILE__))));
  79. define('CAKEPHP_SHELL', true);
  80. if (!defined('CORE_PATH')) {
  81. define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
  82. }
  83. }
  84. }
  85. /**
  86. * Defines current working environment.
  87. *
  88. * @return void
  89. * @throws CakeException
  90. */
  91. protected function _initEnvironment() {
  92. if (!$this->_bootstrap()) {
  93. $message = "Unable to load CakePHP core.\nMake sure " . DS . 'lib' . DS . 'Cake 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 " . DS . 'lib' . DS . 'Cake' . DS . "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. */
  110. protected function _bootstrap() {
  111. define('ROOT', $this->params['root']);
  112. define('APP_DIR', $this->params['app']);
  113. define('APP', $this->params['working'] . DS);
  114. define('WWW_ROOT', APP . $this->params['webroot'] . DS);
  115. if (!is_dir(ROOT . DS . APP_DIR . DS . 'tmp')) {
  116. define('TMP', CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Console' . DS . 'Templates' . DS . 'skel' . DS . 'tmp' . DS);
  117. }
  118. $boot = file_exists(ROOT . DS . APP_DIR . DS . 'Config' . DS . 'bootstrap.php');
  119. require CORE_PATH . 'Cake' . DS . 'bootstrap.php';
  120. if (!file_exists(APP . 'Config' . DS . 'core.php')) {
  121. include_once CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Console' . DS . 'Templates' . DS . 'skel' . DS . 'Config' . DS . 'core.php';
  122. App::build();
  123. }
  124. require_once CAKE . 'Console' . DS . 'ConsoleErrorHandler.php';
  125. set_exception_handler(array('ConsoleErrorHandler', 'handleException'));
  126. set_error_handler(array('ConsoleErrorHandler', 'handleError'), Configure::read('Error.level'));
  127. if (!defined('FULL_BASE_URL')) {
  128. define('FULL_BASE_URL', 'http://localhost');
  129. }
  130. return true;
  131. }
  132. /**
  133. * Dispatches a CLI request
  134. *
  135. * @return boolean
  136. * @throws MissingShellMethodException
  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 An object
  181. * @throws MissingShellFileException 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('AppShell', 'Console');
  188. App::uses($class, $plugin . 'Console/Command');
  189. if (!class_exists($class)) {
  190. throw new MissingShellFileException(array('shell' => $shell));
  191. }
  192. $Shell = new $class();
  193. return $Shell;
  194. }
  195. /**
  196. * Parses command line options and extracts the directory paths from $params
  197. *
  198. * @param array $args Parameters to parse
  199. * @return void
  200. */
  201. public function parseParams($args) {
  202. $this->_parsePaths($args);
  203. $defaults = array(
  204. 'app' => 'app',
  205. 'root' => dirname(dirname(dirname(dirname(__FILE__)))),
  206. 'working' => null,
  207. 'webroot' => 'webroot'
  208. );
  209. $params = array_merge($defaults, array_intersect_key($this->params, $defaults));
  210. $isWin = false;
  211. foreach ($defaults as $default => $value) {
  212. if (strpos($params[$default], '\\') !== false) {
  213. $isWin = true;
  214. break;
  215. }
  216. }
  217. $params = str_replace('\\', '/', $params);
  218. if (isset($params['working'])) {
  219. $params['working'] = trim($params['working']);
  220. }
  221. if (!empty($params['working']) && (!isset($this->args[0]) || isset($this->args[0]) && $this->args[0]{0} !== '.')) {
  222. if (empty($this->params['app']) && $params['working'] != $params['root']) {
  223. $params['root'] = dirname($params['working']);
  224. $params['app'] = basename($params['working']);
  225. } else {
  226. $params['root'] = $params['working'];
  227. }
  228. }
  229. if ($params['app'][0] == '/' || preg_match('/([a-z])(:)/i', $params['app'], $matches)) {
  230. $params['root'] = dirname($params['app']);
  231. } elseif (strpos($params['app'], '/')) {
  232. $params['root'] .= '/' . dirname($params['app']);
  233. }
  234. $params['app'] = basename($params['app']);
  235. $params['working'] = rtrim($params['root'], '/');
  236. if (!$isWin || !preg_match('/^[A-Z]:$/i', $params['app'])) {
  237. $params['working'] .= '/' . $params['app'];
  238. }
  239. if (!empty($matches[0]) || !empty($isWin)) {
  240. $params = str_replace('/', '\\', $params);
  241. }
  242. $this->params = array_merge($this->params, $params);
  243. }
  244. /**
  245. * Parses out the paths from from the argv
  246. *
  247. * @param array $args
  248. * @return void
  249. */
  250. protected function _parsePaths($args) {
  251. $parsed = array();
  252. $keys = array('-working', '--working', '-app', '--app', '-root', '--root');
  253. foreach ($keys as $key) {
  254. $index = array_search($key, $args);
  255. if ($index !== false) {
  256. $keyname = str_replace('-', '', $key);
  257. $valueIndex = $index + 1;
  258. $parsed[$keyname] = $args[$valueIndex];
  259. array_splice($args, $index, 2);
  260. }
  261. }
  262. $this->args = $args;
  263. $this->params = $parsed;
  264. }
  265. /**
  266. * Removes first argument and shifts other arguments up
  267. *
  268. * @return mixed Null if there are no arguments otherwise the shifted argument
  269. */
  270. public function shiftArgs() {
  271. return array_shift($this->args);
  272. }
  273. /**
  274. * Shows console help. Performs an internal dispatch to the CommandList Shell
  275. *
  276. * @return void
  277. */
  278. public function help() {
  279. $this->args = array_merge(array('command_list'), $this->args);
  280. $this->dispatch();
  281. }
  282. /**
  283. * Stop execution of the current script
  284. *
  285. * @param integer|string $status see http://php.net/exit for values
  286. * @return void
  287. */
  288. protected function _stop($status = 0) {
  289. exit($status);
  290. }
  291. }