Application.php 12.6 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

8 9
namespace yii\base;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\web\HttpException;
.  
Qiang Xue committed
12

w  
Qiang Xue committed
13 14 15
/**
 * Application is the base class for all application classes.
 *
w  
Qiang Xue committed
16 17
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
w  
Qiang Xue committed
18
 */
19
abstract class Application extends Module
w  
Qiang Xue committed
20 21
{
	/**
Qiang Xue committed
22
	 * @var string the application name.
w  
Qiang Xue committed
23 24
	 */
	public $name = 'My Application';
Qiang Xue committed
25
	/**
Qiang Xue committed
26
	 * @var string the version of this application.
Qiang Xue committed
27 28
	 */
	public $version = '1.0';
w  
Qiang Xue committed
29
	/**
Qiang Xue committed
30
	 * @var string the charset currently used for the application.
w  
Qiang Xue committed
31 32
	 */
	public $charset = 'UTF-8';
Qiang Xue committed
33 34 35 36 37
	/**
	 * @var string the language that is meant to be used for end users.
	 * @see sourceLanguage
	 */
	public $language = 'en_US';
w  
Qiang Xue committed
38 39
	/**
	 * @var string the language that the application is written in. This mainly refers to
Qiang Xue committed
40
	 * the language that the messages and view files are written in.
.  
Qiang Xue committed
41
	 * @see language
w  
Qiang Xue committed
42
	 */
Qiang Xue committed
43
	public $sourceLanguage = 'en_US';
Qiang Xue committed
44
	/**
Qiang Xue committed
45
	 * @var array IDs of the components that need to be loaded when the application starts.
Qiang Xue committed
46
	 */
Qiang Xue committed
47
	public $preload = array();
Qiang Xue committed
48
	/**
49
	 * @var Controller the currently active controller instance
Qiang Xue committed
50 51
	 */
	public $controller;
Qiang Xue committed
52 53 54 55 56
	/**
	 * @var mixed the layout that should be applied for views in this application. Defaults to 'main'.
	 * If this is false, layout will be disabled.
	 */
	public $layout = 'main';
w  
Qiang Xue committed
57

58
	/**
Alexander Makarov committed
59
	 * @var string Used to reserve memory for fatal error handler.
60 61 62
	 */
	private $_memoryReserve;

w  
Qiang Xue committed
63 64
	/**
	 * Constructor.
65 66
	 * @param array $config name-value pairs that will be used to initialize the object properties.
	 * Note that the configuration must contain both [[id]] and [[basePath]].
67
	 * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
w  
Qiang Xue committed
68
	 */
69
	public function __construct($config = array())
w  
Qiang Xue committed
70
	{
Qiang Xue committed
71
		Yii::$app = $this;
72 73 74 75 76 77 78 79 80
		if (!isset($config['id'])) {
			throw new InvalidConfigException('The "id" configuration is required.');
		}
		if (isset($config['basePath'])) {
			$this->setBasePath($config['basePath']);
			unset($config['basePath']);
		} else {
			throw new InvalidConfigException('The "basePath" configuration is required.');
		}
81

82 83 84 85 86 87 88 89 90 91 92 93 94
		$this->preInit($config);

		$this->registerErrorHandlers();
		$this->registerCoreComponents();

		Component::__construct($config);
	}

	/**
	 * Pre-initializes the application.
	 * This method is called at the beginning of the application constructor.
	 * @param array $config the application configuration
	 */
95
	public function preInit(&$config)
96
	{
97 98
		if (isset($config['vendorPath'])) {
			$this->setVendorPath($config['vendorPath']);
99
			unset($config['vendorPath']);
100 101 102
		} else {
			// set "@vendor"
			$this->getVendorPath();
103
		}
104 105 106 107 108 109
		if (isset($config['runtimePath'])) {
			$this->setRuntimePath($config['runtimePath']);
			unset($config['runtimePath']);
		} else {
			// set "@runtime"
			$this->getRuntimePath();
110
		}
111 112 113 114 115
		if (isset($config['timeZone'])) {
			$this->setTimeZone($config['timeZone']);
			unset($config['timeZone']);
		} elseif (!ini_get('date.timezone')) {
			$this->setTimeZone('UTC');
116
		}
.  
Qiang Xue committed
117
	}
w  
Qiang Xue committed
118

.  
Qiang Xue committed
119
	/**
Qiang Xue committed
120
	 * Registers error handlers.
.  
Qiang Xue committed
121
	 */
Qiang Xue committed
122
	public function registerErrorHandlers()
.  
Qiang Xue committed
123
	{
Qiang Xue committed
124 125 126 127
		if (YII_ENABLE_ERROR_HANDLER) {
			ini_set('display_errors', 0);
			set_exception_handler(array($this, 'handleException'));
			set_error_handler(array($this, 'handleError'), error_reporting());
Qiang Xue committed
128 129 130 131
			// Allocating twice more than required to display memory exhausted error
			// in case of trying to allocate last 1 byte while all memory is taken.
			$this->_memoryReserve = str_repeat('x', 1024 * 256);
			register_shutdown_function(array($this, 'handleFatalError'));
Qiang Xue committed
132
		}
w  
Qiang Xue committed
133 134
	}

Qiang Xue committed
135 136 137 138 139 140 141
	/**
	 * Runs the application.
	 * This is the main entrance of an application.
	 * @return integer the exit status (0 means normal, non-zero values mean abnormal)
	 */
	public function run()
	{
142
		$response = $this->handleRequest($this->getRequest());
143
		$response->send();
144
		return $response->exitStatus;
Qiang Xue committed
145 146
	}

w  
Qiang Xue committed
147
	/**
148 149 150 151 152 153 154
	 * Handles the specified request.
	 *
	 * This method should return an instance of [[Response]] or its child class
	 * which represents the handling result of the request.
	 *
	 * @param Request $request the request to be handled
	 * @return Response the resulting response
Qiang Xue committed
155
	 */
156
	abstract public function handleRequest($request);
157

Qiang Xue committed
158 159
	private $_runtimePath;

w  
Qiang Xue committed
160 161
	/**
	 * Returns the directory that stores runtime files.
162 163
	 * @return string the directory that stores runtime files.
	 * Defaults to the "runtime" subdirectory under [[basePath]].
w  
Qiang Xue committed
164 165 166
	 */
	public function getRuntimePath()
	{
Qiang Xue committed
167
		if ($this->_runtimePath === null) {
w  
Qiang Xue committed
168 169
			$this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
		}
Qiang Xue committed
170
		return $this->_runtimePath;
w  
Qiang Xue committed
171 172 173 174 175 176 177 178
	}

	/**
	 * Sets the directory that stores runtime files.
	 * @param string $path the directory that stores runtime files.
	 */
	public function setRuntimePath($path)
	{
179 180
		$this->_runtimePath = Yii::getAlias($path);
		Yii::setAlias('@runtime', $this->_runtimePath);
w  
Qiang Xue committed
181 182
	}

Qiang Xue committed
183 184 185 186
	private $_vendorPath;

	/**
	 * Returns the directory that stores vendor files.
187
	 * @return string the directory that stores vendor files.
188
	 * Defaults to "vendor" directory under [[basePath]].
Qiang Xue committed
189 190 191
	 */
	public function getVendorPath()
	{
Qiang Xue committed
192
		if ($this->_vendorPath === null) {
Qiang Xue committed
193 194 195 196 197 198 199 200 201 202 203
			$this->setVendorPath($this->getBasePath() . DIRECTORY_SEPARATOR . 'vendor');
		}
		return $this->_vendorPath;
	}

	/**
	 * Sets the directory that stores vendor files.
	 * @param string $path the directory that stores vendor files.
	 */
	public function setVendorPath($path)
	{
Qiang Xue committed
204
		$this->_vendorPath = Yii::getAlias($path);
205
		Yii::setAlias('@vendor', $this->_vendorPath);
Qiang Xue committed
206 207
	}

w  
Qiang Xue committed
208 209 210
	/**
	 * Returns the time zone used by this application.
	 * This is a simple wrapper of PHP function date_default_timezone_get().
211 212
	 * If time zone is not configured in php.ini or application config,
	 * it will be set to UTC by default.
w  
Qiang Xue committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
	 * @return string the time zone used by this application.
	 * @see http://php.net/manual/en/function.date-default-timezone-get.php
	 */
	public function getTimeZone()
	{
		return date_default_timezone_get();
	}

	/**
	 * Sets the time zone used by this application.
	 * This is a simple wrapper of PHP function date_default_timezone_set().
	 * @param string $value the time zone used by this application.
	 * @see http://php.net/manual/en/function.date-default-timezone-set.php
	 */
	public function setTimeZone($value)
	{
		date_default_timezone_set($value);
	}

	/**
	 * Returns the database connection component.
Qiang Xue committed
234
	 * @return \yii\db\Connection the database connection
w  
Qiang Xue committed
235 236 237 238 239 240 241 242
	 */
	public function getDb()
	{
		return $this->getComponent('db');
	}

	/**
	 * Returns the error handler component.
.  
Qiang Xue committed
243
	 * @return ErrorHandler the error handler application component.
w  
Qiang Xue committed
244 245 246 247 248 249 250 251
	 */
	public function getErrorHandler()
	{
		return $this->getComponent('errorHandler');
	}

	/**
	 * Returns the cache component.
.  
Qiang Xue committed
252
	 * @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
w  
Qiang Xue committed
253 254 255 256 257 258
	 */
	public function getCache()
	{
		return $this->getComponent('cache');
	}

259 260 261 262 263 264 265 266 267
	/**
	 * Returns the formatter component.
	 * @return \yii\base\Formatter the formatter application component.
	 */
	public function getFormatter()
	{
		return $this->getComponent('formatter');
	}

w  
Qiang Xue committed
268 269
	/**
	 * Returns the request component.
270
	 * @return \yii\web\Request|\yii\console\Request the request component
w  
Qiang Xue committed
271 272 273 274 275 276
	 */
	public function getRequest()
	{
		return $this->getComponent('request');
	}

Qiang Xue committed
277
	/**
Qiang Xue committed
278 279
	 * Returns the view object.
	 * @return View the view object that is used to render various view files.
Qiang Xue committed
280
	 */
Qiang Xue committed
281
	public function getView()
Qiang Xue committed
282
	{
Qiang Xue committed
283
		return $this->getComponent('view');
Qiang Xue committed
284 285
	}

Qiang Xue committed
286 287 288 289 290 291 292 293 294
	/**
	 * Returns the URL manager for this application.
	 * @return \yii\web\UrlManager the URL manager for this application.
	 */
	public function getUrlManager()
	{
		return $this->getComponent('urlManager');
	}

Qiang Xue committed
295 296 297 298 299 300 301 302 303
	/**
	 * Returns the internationalization (i18n) component
	 * @return \yii\i18n\I18N the internationalization component
	 */
	public function getI18N()
	{
		return $this->getComponent('i18n');
	}

Qiang Xue committed
304
	/**
305
	 * Returns the auth manager for this application.
306
	 * @return \yii\rbac\Manager the auth manager for this application.
Qiang Xue committed
307 308 309
	 */
	public function getAuthManager()
	{
310
		return $this->getComponent('authManager');
Qiang Xue committed
311 312
	}

w  
Qiang Xue committed
313 314 315 316
	/**
	 * Registers the core application components.
	 * @see setComponents
	 */
.  
Qiang Xue committed
317
	public function registerCoreComponents()
w  
Qiang Xue committed
318
	{
.  
Qiang Xue committed
319 320 321 322
		$this->setComponents(array(
			'errorHandler' => array(
				'class' => 'yii\base\ErrorHandler',
			),
323 324 325
			'formatter' => array(
				'class' => 'yii\base\Formatter',
			),
Qiang Xue committed
326 327
			'i18n' => array(
				'class' => 'yii\i18n\I18N',
w  
Qiang Xue committed
328
			),
Qiang Xue committed
329 330
			'urlManager' => array(
				'class' => 'yii\web\UrlManager',
w  
Qiang Xue committed
331
			),
Qiang Xue committed
332 333 334
			'view' => array(
				'class' => 'yii\base\View',
			),
.  
Qiang Xue committed
335
		));
w  
Qiang Xue committed
336
	}
Qiang Xue committed
337

338 339 340
	/**
	 * Handles uncaught PHP exceptions.
	 *
341
	 * This method is implemented as a PHP exception handler.
342
	 *
343
	 * @param \Exception $exception the exception that is not caught
344 345 346 347 348 349 350 351 352 353 354 355
	 */
	public function handleException($exception)
	{
		// disable error capturing to avoid recursive errors while handling exceptions
		restore_error_handler();
		restore_exception_handler();

		try {
			$this->logException($exception);
			if (($handler = $this->getErrorHandler()) !== null) {
				$handler->handle($exception);
			} else {
356
				echo $this->renderException($exception);
357 358
			}
		} catch (\Exception $e) {
359
			// exception could be thrown in ErrorHandler::handle()
360 361 362 363 364 365 366 367 368 369 370 371
			$msg = (string)$e;
			$msg .= "\nPrevious exception:\n";
			$msg .= (string)$exception;
			if (YII_DEBUG) {
				echo $msg;
			}
			$msg .= "\n\$_SERVER = " . var_export($_SERVER, true);
			error_log($msg);
			exit(1);
		}
	}

Qiang Xue committed
372 373 374 375 376 377 378 379 380
	/**
	 * Handles PHP execution errors such as warnings, notices.
	 *
	 * This method is used as a PHP error handler. It will simply raise an `ErrorException`.
	 *
	 * @param integer $code the level of the error raised
	 * @param string $message the error message
	 * @param string $file the filename that the error was raised in
	 * @param integer $line the line number the error was raised at
381 382
	 *
	 * @throws ErrorException
Qiang Xue committed
383 384 385 386
	 */
	public function handleError($code, $message, $file, $line)
	{
		if (error_reporting() !== 0) {
387 388 389 390 391 392 393 394
			// load ErrorException manually here because autoloading them will not work
			// when error occurs while autoloading a class
			if (!class_exists('\\yii\\base\\Exception', false)) {
				require_once(__DIR__ . '/Exception.php');
			}
			if (!class_exists('\\yii\\base\\ErrorException', false)) {
				require_once(__DIR__ . '/ErrorException.php');
			}
395 396 397 398 399
			$exception = new ErrorException($message, $code, $code, $file, $line);

			// in case error appeared in __toString method we can't throw any exception
			$trace = debug_backtrace(false);
			array_shift($trace);
Qiang Xue committed
400 401
			foreach ($trace as $frame) {
				if ($frame['function'] == '__toString') {
402
					$this->handleException($exception);
403
					return;
404 405 406 407
				}
			}

			throw $exception;
Qiang Xue committed
408 409 410 411
		}
	}

	/**
412
	 * Handles fatal PHP errors
Qiang Xue committed
413
	 */
414
	public function handleFatalError()
Qiang Xue committed
415
	{
416 417 418 419 420 421 422 423 424
		// load ErrorException manually here because autoloading them will not work
		// when error occurs while autoloading a class
		if (!class_exists('\\yii\\base\\Exception', false)) {
			require_once(__DIR__ . '/Exception.php');
		}
		if (!class_exists('\\yii\\base\\ErrorException', false)) {
			require_once(__DIR__ . '/ErrorException.php');
		}

425 426 427 428 429 430 431
		$error = error_get_last();

		if (ErrorException::isFatalError($error)) {
			unset($this->_memoryReserve);
			$exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
			// use error_log because it's too late to use Yii log
			error_log($exception);
Qiang Xue committed
432

433 434 435 436
			if (($handler = $this->getErrorHandler()) !== null) {
				$handler->handle($exception);
			} else {
				echo $this->renderException($exception);
Qiang Xue committed
437
			}
438 439

			exit(1);
Qiang Xue committed
440 441 442
		}
	}

Qiang Xue committed
443 444 445
	/**
	 * Renders an exception without using rich format.
	 * @param \Exception $exception the exception to be rendered.
446
	 * @return string the rendering result
Qiang Xue committed
447 448 449
	 */
	public function renderException($exception)
	{
Qiang Xue committed
450
		if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
Qiang Xue committed
451 452 453 454
			$message = $exception->getName() . ': ' . $exception->getMessage();
		} else {
			$message = YII_DEBUG ? (string)$exception : 'Error: ' . $exception->getMessage();
		}
455 456
		if (PHP_SAPI === 'cli') {
			return $message . "\n";
Qiang Xue committed
457
		} else {
458
			return '<pre>' . htmlspecialchars($message, ENT_QUOTES, $this->charset) . '</pre>';
Qiang Xue committed
459 460 461
		}
	}

462 463 464 465
	/**
	 * Logs the given exception
	 * @param \Exception $exception the exception to be logged
	 */
Qiang Xue committed
466 467 468 469 470 471 472 473 474 475 476 477
	protected function logException($exception)
	{
		$category = get_class($exception);
		if ($exception instanceof HttpException) {
			/** @var $exception HttpException */
			$category .= '\\' . $exception->statusCode;
		} elseif ($exception instanceof \ErrorException) {
			/** @var $exception \ErrorException */
			$category .= '\\' . $exception->getSeverity();
		}
		Yii::error((string)$exception, $category);
	}
w  
Qiang Xue committed
478
}