ShellDispatcher.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 bool $bootstrap Should the environment be bootstrapped.
  44. * @return void
  45. */
  46. public function __construct($args = array(), $bootstrap = true) {
  47. set_time_limit(0);
  48. if ($bootstrap) {
  49. $this->_initConstants();
  50. }
  51. $this->parseParams($args);
  52. if ($bootstrap) {
  53. $this->_initEnvironment();
  54. }
  55. }
  56. /**
  57. * Run the dispatcher
  58. *
  59. * @param array $argv The argv from PHP
  60. * @return void
  61. */
  62. public static function run($argv) {
  63. $dispatcher = new ShellDispatcher($argv);
  64. $dispatcher->_stop($dispatcher->dispatch() === false ? 1 : 0);
  65. }
  66. /**
  67. * Defines core configuration.
  68. *
  69. * @return void
  70. */
  71. protected function _initConstants() {
  72. if (function_exists('ini_set')) {
  73. ini_set('html_errors', false);
  74. ini_set('implicit_flush', true);
  75. ini_set('max_execution_time', 0);
  76. }
  77. if (!defined('CAKE_CORE_INCLUDE_PATH')) {
  78. define('DS', DIRECTORY_SEPARATOR);
  79. define('CAKE_CORE_INCLUDE_PATH', dirname(dirname(dirname(__FILE__))));
  80. define('CAKEPHP_SHELL', true);
  81. if (!defined('CORE_PATH')) {
  82. define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
  83. }
  84. }
  85. }
  86. /**
  87. * Defines current working environment.
  88. *
  89. * @return void
  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. private 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. */
  137. public function dispatch() {
  138. $shell = $this->shiftArgs();
  139. if (!$shell) {
  140. $this->help();
  141. return false;
  142. }
  143. if (in_array($shell, array('help', '--help', '-h'))) {
  144. $this->help();
  145. return true;
  146. }
  147. $Shell = $this->_getShell($shell);
  148. $command = null;
  149. if (isset($this->args[0])) {
  150. $command = $this->args[0];
  151. }
  152. if ($Shell instanceof Shell) {
  153. $Shell->initialize();
  154. $Shell->loadTasks();
  155. return $Shell->runCommand($command, $this->args);
  156. }
  157. $methods = array_diff(get_class_methods($Shell), get_class_methods('Shell'));
  158. $added = in_array($command, $methods);
  159. $private = $command[0] == '_' && method_exists($Shell, $command);
  160. if (!$private) {
  161. if ($added) {
  162. $this->shiftArgs();
  163. $Shell->startup();
  164. return $Shell->{$command}();
  165. }
  166. if (method_exists($Shell, 'main')) {
  167. $Shell->startup();
  168. return $Shell->main();
  169. }
  170. }
  171. throw new MissingShellMethodException(array('shell' => $shell, 'method' => $arg));
  172. }
  173. /**
  174. * Get shell to use, either plugin shell or application shell
  175. *
  176. * All paths in the loaded shell paths are searched.
  177. *
  178. * @param string $shell Optionally the name of a plugin
  179. * @return mixed False if no shell could be found or an object on success
  180. * @throws MissingShellFileException, MissingShellClassException when errors are encountered.
  181. */
  182. protected function _getShell($shell) {
  183. list($plugin, $shell) = pluginSplit($shell, true);
  184. $class = Inflector::camelize($shell) . 'Shell';
  185. App::uses('Shell', 'Console');
  186. App::uses('AppShell', 'Console');
  187. App::uses($class, $plugin . 'Console/Command');
  188. if (!class_exists($class)) {
  189. throw new MissingShellFileException(array('shell' => $shell));
  190. }
  191. $Shell = new $class();
  192. return $Shell;
  193. }
  194. /**
  195. * Parses command line options and extracts the directory paths from $params
  196. *
  197. * @param array $params Parameters to parse
  198. */
  199. public function parseParams($args) {
  200. $this->_parsePaths($args);
  201. $defaults = array(
  202. 'app' => 'app',
  203. 'root' => dirname(dirname(dirname(dirname(__FILE__)))),
  204. 'working' => null,
  205. 'webroot' => 'webroot'
  206. );
  207. $params = array_merge($defaults, array_intersect_key($this->params, $defaults));
  208. $isWin = false;
  209. foreach ($defaults as $default => $value) {
  210. if (strpos($params[$default], '\\') !== false) {
  211. $isWin = true;
  212. break;
  213. }
  214. }
  215. $params = str_replace('\\', '/', $params);
  216. if (isset($params['working'])) {
  217. $params['working'] = trim($params['working']);
  218. }
  219. if (!empty($params['working']) && (!isset($this->args[0]) || isset($this->args[0]) && $this->args[0]{0} !== '.')) {
  220. if (empty($this->params['app']) && $params['working'] != $params['root']) {
  221. $params['root'] = dirname($params['working']);
  222. $params['app'] = basename($params['working']);
  223. } else {
  224. $params['root'] = $params['working'];
  225. }
  226. }
  227. if ($params['app'][0] == '/' || preg_match('/([a-z])(:)/i', $params['app'], $matches)) {
  228. $params['root'] = dirname($params['app']);
  229. } elseif (strpos($params['app'], '/')) {
  230. $params['root'] .= '/' . dirname($params['app']);
  231. }
  232. $params['app'] = basename($params['app']);
  233. $params['working'] = rtrim($params['root'], '/');
  234. if (!$isWin || !preg_match('/^[A-Z]:$/i', $params['app'])) {
  235. $params['working'] .= '/' . $params['app'];
  236. }
  237. if (!empty($matches[0]) || !empty($isWin)) {
  238. $params = str_replace('/', '\\', $params);
  239. }
  240. $this->params = array_merge($this->params, $params);
  241. }
  242. /**
  243. * Parses out the paths from from the argv
  244. *
  245. * @return void
  246. */
  247. protected function _parsePaths($args) {
  248. $parsed = array();
  249. $keys = array('-working', '--working', '-app', '--app', '-root', '--root');
  250. foreach ($keys as $key) {
  251. $index = array_search($key, $args);
  252. if ($index !== false) {
  253. $keyname = str_replace('-', '', $key);
  254. $valueIndex = $index + 1;
  255. $parsed[$keyname] = $args[$valueIndex];
  256. array_splice($args, $index, 2);
  257. }
  258. }
  259. $this->args = $args;
  260. $this->params = $parsed;
  261. }
  262. /**
  263. * Removes first argument and shifts other arguments up
  264. *
  265. * @return mixed Null if there are no arguments otherwise the shifted argument
  266. */
  267. public function shiftArgs() {
  268. return array_shift($this->args);
  269. }
  270. /**
  271. * Shows console help. Performs an internal dispatch to the CommandList Shell
  272. *
  273. * @return void
  274. */
  275. public function help() {
  276. $this->args = array_merge(array('command_list'), $this->args);
  277. $this->dispatch();
  278. }
  279. /**
  280. * Stop execution of the current script
  281. *
  282. * @param $status see http://php.net/exit for values
  283. * @return void
  284. */
  285. protected function _stop($status = 0) {
  286. exit($status);
  287. }
  288. }