Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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