PageRenderTime 57ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Console/ShellDispatcher.php

https://bitbucket.org/code_noodle/cakephp
PHP | 357 lines | 231 code | 35 blank | 91 comment | 41 complexity | ab4940c64106cc7d79fd05277b753489 MD5 | raw file
  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. 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. $this->setErrorHandlers();
  125. if (!defined('FULL_BASE_URL')) {
  126. define('FULL_BASE_URL', 'http://localhost');
  127. }
  128. return true;
  129. }
  130. /**
  131. * Set the error/exception handlers for the console
  132. * based on the `Error.consoleHandler`, and `Exception.consoleHandler` values
  133. * if they are set. If they are not set, the default ConsoleErrorHandler will be
  134. * used.
  135. *
  136. * @return void
  137. */
  138. public function setErrorHandlers() {
  139. App::uses('ConsoleErrorHandler', 'Console');
  140. $error = Configure::read('Error');
  141. $exception = Configure::read('Exception');
  142. $errorHandler = new ConsoleErrorHandler();
  143. if (empty($error['consoleHandler'])) {
  144. $error['consoleHandler'] = array($errorHandler, 'handleError');
  145. Configure::write('Error', $error);
  146. }
  147. if (empty($exception['consoleHandler'])) {
  148. $exception['consoleHandler'] = array($errorHandler, 'handleException');
  149. Configure::write('Exception', $exception);
  150. }
  151. set_exception_handler($exception['consoleHandler']);
  152. set_error_handler($error['consoleHandler'], Configure::read('Error.level'));
  153. }
  154. /**
  155. * Dispatches a CLI request
  156. *
  157. * @return boolean
  158. * @throws MissingShellMethodException
  159. */
  160. public function dispatch() {
  161. $shell = $this->shiftArgs();
  162. if (!$shell) {
  163. $this->help();
  164. return false;
  165. }
  166. if (in_array($shell, array('help', '--help', '-h'))) {
  167. $this->help();
  168. return true;
  169. }
  170. $Shell = $this->_getShell($shell);
  171. $command = null;
  172. if (isset($this->args[0])) {
  173. $command = $this->args[0];
  174. }
  175. if ($Shell instanceof Shell) {
  176. $Shell->initialize();
  177. $Shell->loadTasks();
  178. return $Shell->runCommand($command, $this->args);
  179. }
  180. $methods = array_diff(get_class_methods($Shell), get_class_methods('Shell'));
  181. $added = in_array($command, $methods);
  182. $private = $command[0] == '_' && method_exists($Shell, $command);
  183. if (!$private) {
  184. if ($added) {
  185. $this->shiftArgs();
  186. $Shell->startup();
  187. return $Shell->{$command}();
  188. }
  189. if (method_exists($Shell, 'main')) {
  190. $Shell->startup();
  191. return $Shell->main();
  192. }
  193. }
  194. throw new MissingShellMethodException(array('shell' => $shell, 'method' => $command));
  195. }
  196. /**
  197. * Get shell to use, either plugin shell or application shell
  198. *
  199. * All paths in the loaded shell paths are searched.
  200. *
  201. * @param string $shell Optionally the name of a plugin
  202. * @return mixed An object
  203. * @throws MissingShellException when errors are encountered.
  204. */
  205. protected function _getShell($shell) {
  206. list($plugin, $shell) = pluginSplit($shell, true);
  207. $plugin = Inflector::camelize($plugin);
  208. $class = Inflector::camelize($shell) . 'Shell';
  209. App::uses('Shell', 'Console');
  210. App::uses('AppShell', 'Console/Command');
  211. App::uses($class, $plugin . 'Console/Command');
  212. if (!class_exists($class)) {
  213. throw new MissingShellException(array(
  214. 'class' => $class
  215. ));
  216. }
  217. $Shell = new $class();
  218. $Shell->plugin = trim($plugin, '.');
  219. return $Shell;
  220. }
  221. /**
  222. * Parses command line options and extracts the directory paths from $params
  223. *
  224. * @param array $args Parameters to parse
  225. * @return void
  226. */
  227. public function parseParams($args) {
  228. $this->_parsePaths($args);
  229. $defaults = array(
  230. 'app' => 'app',
  231. 'root' => dirname(dirname(dirname(dirname(__FILE__)))),
  232. 'working' => null,
  233. 'webroot' => 'webroot'
  234. );
  235. $params = array_merge($defaults, array_intersect_key($this->params, $defaults));
  236. $isWin = false;
  237. foreach ($defaults as $default => $value) {
  238. if (strpos($params[$default], '\\') !== false) {
  239. $isWin = true;
  240. break;
  241. }
  242. }
  243. $params = str_replace('\\', '/', $params);
  244. if (isset($params['working'])) {
  245. $params['working'] = trim($params['working']);
  246. }
  247. if (!empty($params['working']) && (!isset($this->args[0]) || isset($this->args[0]) && $this->args[0]{0} !== '.')) {
  248. if (empty($this->params['app']) && $params['working'] != $params['root']) {
  249. $params['root'] = dirname($params['working']);
  250. $params['app'] = basename($params['working']);
  251. } else {
  252. $params['root'] = $params['working'];
  253. }
  254. }
  255. if ($params['app'][0] == '/' || preg_match('/([a-z])(:)/i', $params['app'], $matches)) {
  256. $params['root'] = dirname($params['app']);
  257. } elseif (strpos($params['app'], '/')) {
  258. $params['root'] .= '/' . dirname($params['app']);
  259. }
  260. $params['app'] = basename($params['app']);
  261. $params['working'] = rtrim($params['root'], '/');
  262. if (!$isWin || !preg_match('/^[A-Z]:$/i', $params['app'])) {
  263. $params['working'] .= '/' . $params['app'];
  264. }
  265. if (!empty($matches[0]) || !empty($isWin)) {
  266. $params = str_replace('/', '\\', $params);
  267. }
  268. $this->params = array_merge($this->params, $params);
  269. }
  270. /**
  271. * Parses out the paths from from the argv
  272. *
  273. * @param array $args
  274. * @return void
  275. */
  276. protected function _parsePaths($args) {
  277. $parsed = array();
  278. $keys = array('-working', '--working', '-app', '--app', '-root', '--root');
  279. foreach ($keys as $key) {
  280. while (($index = array_search($key, $args)) !== false) {
  281. $keyname = str_replace('-', '', $key);
  282. $valueIndex = $index + 1;
  283. $parsed[$keyname] = $args[$valueIndex];
  284. array_splice($args, $index, 2);
  285. }
  286. }
  287. $this->args = $args;
  288. $this->params = $parsed;
  289. }
  290. /**
  291. * Removes first argument and shifts other arguments up
  292. *
  293. * @return mixed Null if there are no arguments otherwise the shifted argument
  294. */
  295. public function shiftArgs() {
  296. return array_shift($this->args);
  297. }
  298. /**
  299. * Shows console help. Performs an internal dispatch to the CommandList Shell
  300. *
  301. * @return void
  302. */
  303. public function help() {
  304. $this->args = array_merge(array('command_list'), $this->args);
  305. $this->dispatch();
  306. }
  307. /**
  308. * Stop execution of the current script
  309. *
  310. * @param integer|string $status see http://php.net/exit for values
  311. * @return void
  312. */
  313. protected function _stop($status = 0) {
  314. exit($status);
  315. }
  316. }