PageRenderTime 60ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Console/ShellDispatcher.php

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