Application.php 18.1 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.
 *
17
 * @property \yii\rbac\Manager $authManager The auth manager for this application. This property is read-only.
18
 * @property string $basePath The root directory of the application.
19
 * @property \yii\caching\Cache $cache The cache application component. Null if the component is not enabled.
20 21 22 23
 * This property is read-only.
 * @property \yii\db\Connection $db The database connection. This property is read-only.
 * @property ErrorHandler $errorHandler The error handler application component. This property is read-only.
 * @property \yii\base\Formatter $formatter The formatter application component. This property is read-only.
24
 * @property \yii\i18n\I18N $i18n The internationalization component. This property is read-only.
25 26 27 28
 * @property \yii\log\Logger $log The log component. This property is read-only.
 * @property \yii\web\Request|\yii\console\Request $request The request component. This property is read-only.
 * @property string $runtimePath The directory that stores runtime files. Defaults to the "runtime"
 * subdirectory under [[basePath]].
29
 * @property string $timeZone The time zone used by this application.
30 31 32 33
 * @property string $uniqueId The unique ID of the module. This property is read-only.
 * @property \yii\web\UrlManager $urlManager The URL manager for this application. This property is read-only.
 * @property string $vendorPath The directory that stores vendor files. Defaults to "vendor" directory under
 * [[basePath]].
Qiang Xue committed
34 35
 * @property View|\yii\web\View $view The view object that is used to render various view files. This property
 * is read-only.
36
 *
w  
Qiang Xue committed
37 38
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
w  
Qiang Xue committed
39
 */
40
abstract class Application extends Module
w  
Qiang Xue committed
41
{
Qiang Xue committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
	/**
	 * @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';
59 60 61 62 63 64 65

	/**
	 * @var string the namespace that controller classes are in. If not set,
	 * it will use the "app\controllers" namespace.
	 */
	public $controllerNamespace = 'app\\controllers';

w  
Qiang Xue committed
66
	/**
Qiang Xue committed
67
	 * @var string the application name.
w  
Qiang Xue committed
68 69
	 */
	public $name = 'My Application';
Qiang Xue committed
70
	/**
Qiang Xue committed
71
	 * @var string the version of this application.
Qiang Xue committed
72 73
	 */
	public $version = '1.0';
w  
Qiang Xue committed
74
	/**
Qiang Xue committed
75
	 * @var string the charset currently used for the application.
w  
Qiang Xue committed
76 77
	 */
	public $charset = 'UTF-8';
Qiang Xue committed
78 79 80 81
	/**
	 * @var string the language that is meant to be used for end users.
	 * @see sourceLanguage
	 */
82
	public $language = 'en-US';
w  
Qiang Xue committed
83 84
	/**
	 * @var string the language that the application is written in. This mainly refers to
Qiang Xue committed
85
	 * the language that the messages and view files are written in.
.  
Qiang Xue committed
86
	 * @see language
w  
Qiang Xue committed
87
	 */
88
	public $sourceLanguage = 'en-US';
Qiang Xue committed
89
	/**
90
	 * @var Controller the currently active controller instance
Qiang Xue committed
91 92
	 */
	public $controller;
Qiang Xue committed
93
	/**
94
	 * @var string|boolean the layout that should be applied for views in this application. Defaults to 'main'.
Qiang Xue committed
95 96 97
	 * If this is false, layout will be disabled.
	 */
	public $layout = 'main';
98 99 100 101 102 103
	/**
	 * @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.
	 */
104
	public $memoryReserveSize = 262144;
Qiang Xue committed
105 106 107 108 109 110 111 112 113 114 115 116
	/**
	 * @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;
Qiang Xue committed
117 118 119 120 121 122 123 124 125 126 127 128
	/**
	 * @var array list of installed Yii extensions. Each array element represents a single extension
	 * with the following structure:
	 *
	 * ~~~
	 * [
	 *     'name' => 'extension name',
	 *     'version' => 'version number',
	 *     'bootstrap' => 'BootstrapClassName',
	 * ]
	 * ~~~
	 */
129
	public $extensions = [];
w  
Qiang Xue committed
130

131
	/**
Alexander Makarov committed
132
	 * @var string Used to reserve memory for fatal error handler.
133 134 135
	 */
	private $_memoryReserve;

w  
Qiang Xue committed
136 137
	/**
	 * Constructor.
138 139
	 * @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]].
140
	 * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
w  
Qiang Xue committed
141
	 */
Alexander Makarov committed
142
	public function __construct($config = [])
w  
Qiang Xue committed
143
	{
Qiang Xue committed
144
		Yii::$app = $this;
145

146 147 148 149 150 151 152 153 154 155
		$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.
156 157
	 * It initializes several important application properties.
	 * If you override this method, please make sure you call the parent implementation.
158
	 * @param array $config the application configuration
159
	 * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
160
	 */
161
	public function preInit(&$config)
162
	{
163 164 165 166 167 168 169 170 171 172
		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.');
		}

173 174
		if (isset($config['vendorPath'])) {
			$this->setVendorPath($config['vendorPath']);
175
			unset($config['vendorPath']);
176 177 178
		} else {
			// set "@vendor"
			$this->getVendorPath();
179
		}
180 181 182 183 184 185
		if (isset($config['runtimePath'])) {
			$this->setRuntimePath($config['runtimePath']);
			unset($config['runtimePath']);
		} else {
			// set "@runtime"
			$this->getRuntimePath();
186
		}
187

188 189 190 191 192
		if (isset($config['timeZone'])) {
			$this->setTimeZone($config['timeZone']);
			unset($config['timeZone']);
		} elseif (!ini_get('date.timezone')) {
			$this->setTimeZone('UTC');
193
		}
.  
Qiang Xue committed
194
	}
w  
Qiang Xue committed
195

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
	/**
	 * @inheritdoc
	 */
	public function init()
	{
		parent::init();
		$this->initExtensions($this->extensions);
	}

	/**
	 * Initializes the extensions.
	 * @param array $extensions the extensions to be initialized. Please refer to [[extensions]]
	 * for the structure of the extension array.
	 */
	protected function initExtensions($extensions)
	{
		foreach ($extensions as $extension) {
213 214 215 216 217
			if (!empty($extension['alias'])) {
				foreach ($extension['alias'] as $name => $path) {
					Yii::setAlias($name, $path);
				}
			}
218 219 220 221 222 223 224 225
			if (isset($extension['bootstrap'])) {
				/** @var Extension $class */
				$class = $extension['bootstrap'];
				$class::init();
			}
		}
	}

Qiang Xue committed
226 227 228 229 230 231 232 233 234 235
	/**
	 * 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
236
	/**
Qiang Xue committed
237
	 * Registers error handlers.
.  
Qiang Xue committed
238
	 */
Qiang Xue committed
239
	public function registerErrorHandlers()
.  
Qiang Xue committed
240
	{
Qiang Xue committed
241
		if (YII_ENABLE_ERROR_HANDLER) {
242
			ini_set('display_errors', 0);
Alexander Makarov committed
243 244
			set_exception_handler([$this, 'handleException']);
			set_error_handler([$this, 'handleError'], error_reporting());
245 246
			if ($this->memoryReserveSize > 0) {
				$this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
247
			}
Alexander Makarov committed
248
			register_shutdown_function([$this, 'handleFatalError']);
Qiang Xue committed
249
		}
w  
Qiang Xue committed
250 251
	}

Qiang Xue committed
252 253 254 255 256 257 258 259 260 261
	/**
	 * 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 '';
	}

262
	/**
Qiang Xue committed
263
	 * Sets the root directory of the application and the @app alias.
264 265
	 * This method can only be invoked at the beginning of the constructor.
	 * @param string $path the root directory of the application.
266
	 * @property string the root directory of the application.
267 268 269 270 271 272 273 274
	 * @throws InvalidParamException if the directory does not exist.
	 */
	public function setBasePath($path)
	{
		parent::setBasePath($path);
		Yii::setAlias('@app', $this->getBasePath());
	}

Qiang Xue committed
275 276 277 278 279 280 281
	/**
	 * 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
282
		$this->trigger(self::EVENT_BEFORE_REQUEST);
283
		$response = $this->handleRequest($this->getRequest());
Qiang Xue committed
284
		$this->trigger(self::EVENT_AFTER_REQUEST);
285
		$response->send();
286
		return $response->exitStatus;
Qiang Xue committed
287 288
	}

w  
Qiang Xue committed
289
	/**
290 291 292 293 294 295 296
	 * 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
297
	 */
298
	abstract public function handleRequest($request);
299

300

Qiang Xue committed
301 302
	private $_runtimePath;

w  
Qiang Xue committed
303 304
	/**
	 * Returns the directory that stores runtime files.
305 306
	 * @return string the directory that stores runtime files.
	 * Defaults to the "runtime" subdirectory under [[basePath]].
w  
Qiang Xue committed
307 308 309
	 */
	public function getRuntimePath()
	{
Qiang Xue committed
310
		if ($this->_runtimePath === null) {
w  
Qiang Xue committed
311 312
			$this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
		}
Qiang Xue committed
313
		return $this->_runtimePath;
w  
Qiang Xue committed
314 315 316 317 318 319 320 321
	}

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

Qiang Xue committed
326 327 328 329
	private $_vendorPath;

	/**
	 * Returns the directory that stores vendor files.
330
	 * @return string the directory that stores vendor files.
331
	 * Defaults to "vendor" directory under [[basePath]].
Qiang Xue committed
332 333 334
	 */
	public function getVendorPath()
	{
Qiang Xue committed
335
		if ($this->_vendorPath === null) {
Qiang Xue committed
336 337 338 339 340 341 342 343 344 345 346
			$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
347
		$this->_vendorPath = Yii::getAlias($path);
348
		Yii::setAlias('@vendor', $this->_vendorPath);
Qiang Xue committed
349 350
	}

w  
Qiang Xue committed
351 352 353
	/**
	 * Returns the time zone used by this application.
	 * This is a simple wrapper of PHP function date_default_timezone_get().
354 355
	 * If time zone is not configured in php.ini or application config,
	 * it will be set to UTC by default.
w  
Qiang Xue committed
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
	 * @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
377
	 * @return \yii\db\Connection the database connection
w  
Qiang Xue committed
378 379 380 381 382 383
	 */
	public function getDb()
	{
		return $this->getComponent('db');
	}

Qiang Xue committed
384 385 386 387 388 389 390 391 392
	/**
	 * Returns the log component.
	 * @return \yii\log\Logger the log component
	 */
	public function getLog()
	{
		return $this->getComponent('log');
	}

w  
Qiang Xue committed
393 394
	/**
	 * Returns the error handler component.
.  
Qiang Xue committed
395
	 * @return ErrorHandler the error handler application component.
w  
Qiang Xue committed
396 397 398 399 400 401 402 403
	 */
	public function getErrorHandler()
	{
		return $this->getComponent('errorHandler');
	}

	/**
	 * Returns the cache component.
.  
Qiang Xue committed
404
	 * @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
w  
Qiang Xue committed
405 406 407 408 409 410
	 */
	public function getCache()
	{
		return $this->getComponent('cache');
	}

411 412 413 414 415 416 417 418 419
	/**
	 * Returns the formatter component.
	 * @return \yii\base\Formatter the formatter application component.
	 */
	public function getFormatter()
	{
		return $this->getComponent('formatter');
	}

w  
Qiang Xue committed
420 421
	/**
	 * Returns the request component.
422
	 * @return \yii\web\Request|\yii\console\Request the request component
w  
Qiang Xue committed
423 424 425 426 427 428
	 */
	public function getRequest()
	{
		return $this->getComponent('request');
	}

Qiang Xue committed
429
	/**
Qiang Xue committed
430
	 * Returns the view object.
Qiang Xue committed
431
	 * @return View|\yii\web\View the view object that is used to render various view files.
Qiang Xue committed
432
	 */
Qiang Xue committed
433
	public function getView()
Qiang Xue committed
434
	{
Qiang Xue committed
435
		return $this->getComponent('view');
Qiang Xue committed
436 437
	}

Qiang Xue committed
438 439 440 441 442 443 444 445 446
	/**
	 * 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
447 448 449 450
	/**
	 * Returns the internationalization (i18n) component
	 * @return \yii\i18n\I18N the internationalization component
	 */
451
	public function getI18n()
Qiang Xue committed
452 453 454 455
	{
		return $this->getComponent('i18n');
	}

Qiang Xue committed
456
	/**
457
	 * Returns the auth manager for this application.
458
	 * @return \yii\rbac\Manager the auth manager for this application.
Qiang Xue committed
459 460 461
	 */
	public function getAuthManager()
	{
462
		return $this->getComponent('authManager');
Qiang Xue committed
463 464
	}

w  
Qiang Xue committed
465 466 467 468
	/**
	 * Registers the core application components.
	 * @see setComponents
	 */
.  
Qiang Xue committed
469
	public function registerCoreComponents()
w  
Qiang Xue committed
470
	{
Alexander Makarov committed
471 472 473 474 475 476
		$this->setComponents([
			'log' => ['class' => 'yii\log\Logger'],
			'errorHandler' => ['class' => 'yii\base\ErrorHandler'],
			'formatter' => ['class' => 'yii\base\Formatter'],
			'i18n' => ['class' => 'yii\i18n\I18N'],
			'urlManager' => ['class' => 'yii\web\UrlManager'],
Alexander Makarov committed
477
			'view' => ['class' => 'yii\web\View'],
Alexander Makarov committed
478
		]);
w  
Qiang Xue committed
479
	}
Qiang Xue committed
480

481 482 483
	/**
	 * Handles uncaught PHP exceptions.
	 *
484
	 * This method is implemented as a PHP exception handler.
485
	 *
486
	 * @param \Exception $exception the exception that is not caught
487 488 489 490 491 492 493 494 495 496 497
	 */
	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 {
498
				echo $this->renderException($exception);
499 500
			}
		} catch (\Exception $e) {
501
			// exception could be thrown in ErrorHandler::handle()
502 503 504 505
			$msg = (string)$e;
			$msg .= "\nPrevious exception:\n";
			$msg .= (string)$exception;
			if (YII_DEBUG) {
506 507 508 509 510
				if (PHP_SAPI === 'cli') {
					echo $msg . "\n";
				} else {
					echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, $this->charset) . '</pre>';
				}
511 512 513 514 515 516 517
			}
			$msg .= "\n\$_SERVER = " . var_export($_SERVER, true);
			error_log($msg);
			exit(1);
		}
	}

Qiang Xue committed
518 519 520 521 522 523 524 525 526
	/**
	 * 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
527 528
	 *
	 * @throws ErrorException
Qiang Xue committed
529 530 531 532
	 */
	public function handleError($code, $message, $file, $line)
	{
		if (error_reporting() !== 0) {
533 534 535 536 537 538 539 540
			// 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');
			}
541 542 543 544 545
			$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
546 547
			foreach ($trace as $frame) {
				if ($frame['function'] == '__toString') {
548
					$this->handleException($exception);
549
					exit(1);
550 551 552 553
				}
			}

			throw $exception;
Qiang Xue committed
554 555 556 557
		}
	}

	/**
558
	 * Handles fatal PHP errors
Qiang Xue committed
559
	 */
560
	public function handleFatalError()
Qiang Xue committed
561
	{
562 563
		unset($this->_memoryReserve);

564 565 566 567 568 569 570 571 572
		// 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');
		}

573 574 575 576 577 578
		$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
579

580 581 582 583
			if (($handler = $this->getErrorHandler()) !== null) {
				$handler->handle($exception);
			} else {
				echo $this->renderException($exception);
Qiang Xue committed
584
			}
585 586

			exit(1);
Qiang Xue committed
587 588 589
		}
	}

Qiang Xue committed
590 591 592
	/**
	 * Renders an exception without using rich format.
	 * @param \Exception $exception the exception to be rendered.
593
	 * @return string the rendering result
Qiang Xue committed
594 595 596
	 */
	public function renderException($exception)
	{
Qiang Xue committed
597
		if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
Qiang Xue committed
598
			$message = $exception->getName() . ': ' . $exception->getMessage();
Qiang Xue committed
599 600 601
			if (Yii::$app->controller instanceof \yii\console\Controller) {
				$message = Yii::$app->controller->ansiFormat($message, Console::FG_RED);
			}
Qiang Xue committed
602 603 604
		} else {
			$message = YII_DEBUG ? (string)$exception : 'Error: ' . $exception->getMessage();
		}
605 606
		if (PHP_SAPI === 'cli') {
			return $message . "\n";
Qiang Xue committed
607
		} else {
608
			return '<pre>' . htmlspecialchars($message, ENT_QUOTES, $this->charset) . '</pre>';
Qiang Xue committed
609 610 611
		}
	}

612 613 614 615
	/**
	 * Logs the given exception
	 * @param \Exception $exception the exception to be logged
	 */
Qiang Xue committed
616 617 618 619 620 621 622 623 624 625
	protected function logException($exception)
	{
		$category = get_class($exception);
		if ($exception instanceof HttpException) {
			$category .= '\\' . $exception->statusCode;
		} elseif ($exception instanceof \ErrorException) {
			$category .= '\\' . $exception->getSeverity();
		}
		Yii::error((string)$exception, $category);
	}
w  
Qiang Xue committed
626
}