Application.php 14.9 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\helpers\Console;
Qiang Xue committed
12
use yii\web\HttpException;
.  
Qiang Xue committed
13

w  
Qiang Xue committed
14 15 16
/**
 * Application is the base class for all application classes.
 *
w  
Qiang Xue committed
17 18
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
w  
Qiang Xue committed
19
 */
20
abstract class Application extends Module
w  
Qiang Xue committed
21
{
Qiang Xue committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
	/**
	 * @event Event an event raised before the application starts to handle a request.
	 */
	const EVENT_BEFORE_REQUEST = 'beforeRequest';
	/**
	 * @event Event an event raised after the application successfully handles a request (before the response is sent out).
	 */
	const EVENT_AFTER_REQUEST = 'afterRequest';
	/**
	 * @event ActionEvent an event raised before executing a controller action.
	 * You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
	 */
	const EVENT_BEFORE_ACTION = 'beforeAction';
	/**
	 * @event ActionEvent an event raised after executing a controller action.
	 */
	const EVENT_AFTER_ACTION = 'afterAction';
w  
Qiang Xue committed
39
	/**
Qiang Xue committed
40
	 * @var string the application name.
w  
Qiang Xue committed
41 42
	 */
	public $name = 'My Application';
Qiang Xue committed
43
	/**
Qiang Xue committed
44
	 * @var string the version of this application.
Qiang Xue committed
45 46
	 */
	public $version = '1.0';
w  
Qiang Xue committed
47
	/**
Qiang Xue committed
48
	 * @var string the charset currently used for the application.
w  
Qiang Xue committed
49 50
	 */
	public $charset = 'UTF-8';
Qiang Xue committed
51 52 53 54 55
	/**
	 * @var string the language that is meant to be used for end users.
	 * @see sourceLanguage
	 */
	public $language = 'en_US';
w  
Qiang Xue committed
56 57
	/**
	 * @var string the language that the application is written in. This mainly refers to
Qiang Xue committed
58
	 * the language that the messages and view files are written in.
.  
Qiang Xue committed
59
	 * @see language
w  
Qiang Xue committed
60
	 */
Qiang Xue committed
61
	public $sourceLanguage = 'en_US';
Qiang Xue committed
62
	/**
Qiang Xue committed
63
	 * @var array IDs of the components that need to be loaded when the application starts.
Qiang Xue committed
64
	 */
Qiang Xue committed
65
	public $preload = array();
Qiang Xue committed
66
	/**
67
	 * @var Controller the currently active controller instance
Qiang Xue committed
68 69
	 */
	public $controller;
Qiang Xue committed
70 71 72 73 74
	/**
	 * @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';
75 76 77 78 79 80
	/**
	 * @var integer the size of the reserved memory. A portion of memory is pre-allocated so that
	 * when an out-of-memory issue occurs, the error handler is able to handle the error with
	 * the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
	 * Defaults to 256KB.
	 */
81
	public $memoryReserveSize = 262144;
Qiang Xue committed
82 83 84 85 86 87 88 89 90 91 92 93
	/**
	 * @var string the requested route
	 */
	public $requestedRoute;
	/**
	 * @var Action the requested Action. If null, it means the request cannot be resolved into an action.
	 */
	public $requestedAction;
	/**
	 * @var array the parameters supplied to the requested action.
	 */
	public $requestedParams;
w  
Qiang Xue committed
94

95
	/**
Alexander Makarov committed
96
	 * @var string Used to reserve memory for fatal error handler.
97 98 99
	 */
	private $_memoryReserve;

w  
Qiang Xue committed
100 101
	/**
	 * Constructor.
102 103
	 * @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]].
104
	 * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
w  
Qiang Xue committed
105
	 */
106
	public function __construct($config = array())
w  
Qiang Xue committed
107
	{
Qiang Xue committed
108
		Yii::$app = $this;
109 110 111 112 113 114 115 116 117
		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.');
		}
118

119 120 121 122 123 124 125 126 127 128 129 130 131
		$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
	 */
132
	public function preInit(&$config)
133
	{
134 135
		if (isset($config['vendorPath'])) {
			$this->setVendorPath($config['vendorPath']);
136
			unset($config['vendorPath']);
137 138 139
		} else {
			// set "@vendor"
			$this->getVendorPath();
140
		}
141 142 143 144 145 146
		if (isset($config['runtimePath'])) {
			$this->setRuntimePath($config['runtimePath']);
			unset($config['runtimePath']);
		} else {
			// set "@runtime"
			$this->getRuntimePath();
147
		}
148 149 150 151 152
		if (isset($config['timeZone'])) {
			$this->setTimeZone($config['timeZone']);
			unset($config['timeZone']);
		} elseif (!ini_get('date.timezone')) {
			$this->setTimeZone('UTC');
153
		}
.  
Qiang Xue committed
154
	}
w  
Qiang Xue committed
155

Qiang Xue committed
156 157 158 159 160 161 162 163 164 165
	/**
	 * Loads components that are declared in [[preload]].
	 * @throws InvalidConfigException if a component or module to be preloaded is unknown
	 */
	public function preloadComponents()
	{
		$this->getComponent('log');
		parent::preloadComponents();
	}

.  
Qiang Xue committed
166
	/**
Qiang Xue committed
167
	 * Registers error handlers.
.  
Qiang Xue committed
168
	 */
Qiang Xue committed
169
	public function registerErrorHandlers()
.  
Qiang Xue committed
170
	{
Qiang Xue committed
171
		if (YII_ENABLE_ERROR_HANDLER) {
172
			//ini_set('display_errors', 0);
Qiang Xue committed
173 174
			set_exception_handler(array($this, 'handleException'));
			set_error_handler(array($this, 'handleError'), error_reporting());
175 176
			if ($this->memoryReserveSize > 0) {
				$this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
177
			}
Qiang Xue committed
178
			register_shutdown_function(array($this, 'handleFatalError'));
Qiang Xue committed
179
		}
w  
Qiang Xue committed
180 181
	}

Qiang Xue committed
182 183 184 185 186 187 188 189 190 191
	/**
	 * Returns an ID that uniquely identifies this module among all modules within the current application.
	 * Since this is an application instance, it will always return an empty string.
	 * @return string the unique ID of the module.
	 */
	public function getUniqueId()
	{
		return '';
	}

Qiang Xue committed
192 193 194 195 196 197 198
	/**
	 * 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()
	{
Qiang Xue committed
199
		$this->trigger(self::EVENT_BEFORE_REQUEST);
200
		$response = $this->handleRequest($this->getRequest());
Qiang Xue committed
201
		$this->trigger(self::EVENT_AFTER_REQUEST);
202
		$response->send();
203
		return $response->exitStatus;
Qiang Xue committed
204 205
	}

w  
Qiang Xue committed
206
	/**
207 208 209 210 211 212 213
	 * 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
214
	 */
215
	abstract public function handleRequest($request);
216

217

Qiang Xue committed
218 219
	private $_runtimePath;

w  
Qiang Xue committed
220 221
	/**
	 * Returns the directory that stores runtime files.
222 223
	 * @return string the directory that stores runtime files.
	 * Defaults to the "runtime" subdirectory under [[basePath]].
w  
Qiang Xue committed
224 225 226
	 */
	public function getRuntimePath()
	{
Qiang Xue committed
227
		if ($this->_runtimePath === null) {
w  
Qiang Xue committed
228 229
			$this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
		}
Qiang Xue committed
230
		return $this->_runtimePath;
w  
Qiang Xue committed
231 232 233 234 235 236 237 238
	}

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

Qiang Xue committed
243 244 245 246
	private $_vendorPath;

	/**
	 * Returns the directory that stores vendor files.
247
	 * @return string the directory that stores vendor files.
248
	 * Defaults to "vendor" directory under [[basePath]].
Qiang Xue committed
249 250 251
	 */
	public function getVendorPath()
	{
Qiang Xue committed
252
		if ($this->_vendorPath === null) {
Qiang Xue committed
253 254 255 256 257 258 259 260 261 262 263
			$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
264
		$this->_vendorPath = Yii::getAlias($path);
265
		Yii::setAlias('@vendor', $this->_vendorPath);
Qiang Xue committed
266 267
	}

w  
Qiang Xue committed
268 269 270
	/**
	 * Returns the time zone used by this application.
	 * This is a simple wrapper of PHP function date_default_timezone_get().
271 272
	 * If time zone is not configured in php.ini or application config,
	 * it will be set to UTC by default.
w  
Qiang Xue committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
	 * @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
294
	 * @return \yii\db\Connection the database connection
w  
Qiang Xue committed
295 296 297 298 299 300
	 */
	public function getDb()
	{
		return $this->getComponent('db');
	}

Qiang Xue committed
301 302 303 304 305 306 307 308 309
	/**
	 * Returns the log component.
	 * @return \yii\log\Logger the log component
	 */
	public function getLog()
	{
		return $this->getComponent('log');
	}

w  
Qiang Xue committed
310 311
	/**
	 * Returns the error handler component.
.  
Qiang Xue committed
312
	 * @return ErrorHandler the error handler application component.
w  
Qiang Xue committed
313 314 315 316 317 318 319 320
	 */
	public function getErrorHandler()
	{
		return $this->getComponent('errorHandler');
	}

	/**
	 * Returns the cache component.
.  
Qiang Xue committed
321
	 * @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
w  
Qiang Xue committed
322 323 324 325 326 327
	 */
	public function getCache()
	{
		return $this->getComponent('cache');
	}

328 329 330 331 332 333 334 335 336
	/**
	 * Returns the formatter component.
	 * @return \yii\base\Formatter the formatter application component.
	 */
	public function getFormatter()
	{
		return $this->getComponent('formatter');
	}

w  
Qiang Xue committed
337 338
	/**
	 * Returns the request component.
339
	 * @return \yii\web\Request|\yii\console\Request the request component
w  
Qiang Xue committed
340 341 342 343 344 345
	 */
	public function getRequest()
	{
		return $this->getComponent('request');
	}

Qiang Xue committed
346
	/**
Qiang Xue committed
347 348
	 * Returns the view object.
	 * @return View the view object that is used to render various view files.
Qiang Xue committed
349
	 */
Qiang Xue committed
350
	public function getView()
Qiang Xue committed
351
	{
Qiang Xue committed
352
		return $this->getComponent('view');
Qiang Xue committed
353 354
	}

Qiang Xue committed
355 356 357 358 359 360 361 362 363
	/**
	 * 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
364 365 366 367 368 369 370 371 372
	/**
	 * Returns the internationalization (i18n) component
	 * @return \yii\i18n\I18N the internationalization component
	 */
	public function getI18N()
	{
		return $this->getComponent('i18n');
	}

Qiang Xue committed
373
	/**
374
	 * Returns the auth manager for this application.
375
	 * @return \yii\rbac\Manager the auth manager for this application.
Qiang Xue committed
376 377 378
	 */
	public function getAuthManager()
	{
379
		return $this->getComponent('authManager');
Qiang Xue committed
380 381
	}

w  
Qiang Xue committed
382 383 384 385
	/**
	 * Registers the core application components.
	 * @see setComponents
	 */
.  
Qiang Xue committed
386
	public function registerCoreComponents()
w  
Qiang Xue committed
387
	{
.  
Qiang Xue committed
388
		$this->setComponents(array(
Qiang Xue committed
389 390 391
			'log' => array(
				'class' => 'yii\log\Logger',
			),
.  
Qiang Xue committed
392 393 394
			'errorHandler' => array(
				'class' => 'yii\base\ErrorHandler',
			),
395 396 397
			'formatter' => array(
				'class' => 'yii\base\Formatter',
			),
Qiang Xue committed
398 399
			'i18n' => array(
				'class' => 'yii\i18n\I18N',
w  
Qiang Xue committed
400
			),
Qiang Xue committed
401 402
			'urlManager' => array(
				'class' => 'yii\web\UrlManager',
w  
Qiang Xue committed
403
			),
Qiang Xue committed
404 405 406
			'view' => array(
				'class' => 'yii\base\View',
			),
.  
Qiang Xue committed
407
		));
w  
Qiang Xue committed
408
	}
Qiang Xue committed
409

410 411 412
	/**
	 * Handles uncaught PHP exceptions.
	 *
413
	 * This method is implemented as a PHP exception handler.
414
	 *
415
	 * @param \Exception $exception the exception that is not caught
416 417 418 419 420 421 422 423 424 425 426 427
	 */
	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 {
428
				echo $this->renderException($exception);
429 430
			}
		} catch (\Exception $e) {
431
			// exception could be thrown in ErrorHandler::handle()
432 433 434 435 436 437 438 439 440 441 442 443
			$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
444 445 446 447 448 449 450 451 452
	/**
	 * 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
453 454
	 *
	 * @throws ErrorException
Qiang Xue committed
455 456 457 458
	 */
	public function handleError($code, $message, $file, $line)
	{
		if (error_reporting() !== 0) {
459 460 461 462 463 464 465 466
			// 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');
			}
467 468 469 470 471
			$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
472 473
			foreach ($trace as $frame) {
				if ($frame['function'] == '__toString') {
474
					$this->handleException($exception);
475
					return;
476 477 478 479
				}
			}

			throw $exception;
Qiang Xue committed
480 481 482 483
		}
	}

	/**
484
	 * Handles fatal PHP errors
Qiang Xue committed
485
	 */
486
	public function handleFatalError()
Qiang Xue committed
487
	{
488 489
		unset($this->_memoryReserve);

490 491 492 493 494 495 496 497 498
		// 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');
		}

499 500 501 502 503 504
		$error = error_get_last();

		if (ErrorException::isFatalError($error)) {
			$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
505

506 507 508 509
			if (($handler = $this->getErrorHandler()) !== null) {
				$handler->handle($exception);
			} else {
				echo $this->renderException($exception);
Qiang Xue committed
510
			}
511 512

			exit(1);
Qiang Xue committed
513 514 515
		}
	}

Qiang Xue committed
516 517 518
	/**
	 * Renders an exception without using rich format.
	 * @param \Exception $exception the exception to be rendered.
519
	 * @return string the rendering result
Qiang Xue committed
520 521 522
	 */
	public function renderException($exception)
	{
Qiang Xue committed
523
		if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
Qiang Xue committed
524
			$message = $exception->getName() . ': ' . $exception->getMessage();
Qiang Xue committed
525 526 527
			if (Yii::$app->controller instanceof \yii\console\Controller) {
				$message = Yii::$app->controller->ansiFormat($message, Console::FG_RED);
			}
Qiang Xue committed
528 529 530
		} else {
			$message = YII_DEBUG ? (string)$exception : 'Error: ' . $exception->getMessage();
		}
531 532
		if (PHP_SAPI === 'cli') {
			return $message . "\n";
Qiang Xue committed
533
		} else {
534
			return '<pre>' . htmlspecialchars($message, ENT_QUOTES, $this->charset) . '</pre>';
Qiang Xue committed
535 536 537
		}
	}

538 539 540 541
	/**
	 * Logs the given exception
	 * @param \Exception $exception the exception to be logged
	 */
Qiang Xue committed
542 543 544 545 546 547 548 549 550 551 552 553
	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
554
}