Yii2 Bootstrap 3
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

523 lines
14 KiB

14 years ago
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
14 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
12 years ago
use Yii;
use yii\web\HttpException;
13 years ago
14 years ago
/**
* Application is the base class for all application classes.
*
14 years ago
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
14 years ago
*/
13 years ago
class Application extends Module
14 years ago
{
/**
* @event Event an event that is triggered at the beginning of [[run()]].
*/
const EVENT_BEFORE_RUN = 'beforeRun';
/**
* @event Event an event that is triggered at the end of [[run()]].
*/
const EVENT_AFTER_RUN = 'afterRun';
14 years ago
/**
* @var string the application name.
14 years ago
*/
public $name = 'My Application';
/**
* @var string the version of this application.
13 years ago
*/
public $version = '1.0';
/**
* @var string the charset currently used for the application.
14 years ago
*/
public $charset = 'UTF-8';
/**
* @var string the language that is meant to be used for end users.
* @see sourceLanguage
*/
public $language = 'en_US';
/**
14 years ago
* @var string the language that the application is written in. This mainly refers to
* the language that the messages and view files are written in.
13 years ago
* @see language
14 years ago
*/
public $sourceLanguage = 'en_US';
13 years ago
/**
* @var array IDs of the components that need to be loaded when the application starts.
13 years ago
*/
public $preload = array();
/**
* @var \yii\web\Controller|\yii\console\Controller the currently active controller instance
*/
public $controller;
13 years ago
/**
* @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';
14 years ago
private $_ended = false;
/**
* @var string Used to reserve memory for fatal error handler.
*/
private $_memoryReserve;
/**
14 years ago
* Constructor.
* @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]].
* @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
14 years ago
*/
public function __construct($config = array())
14 years ago
{
Yii::$app = $this;
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.');
}
$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
*/
public function preInit(&$config)
{
if (isset($config['vendorPath'])) {
$this->setVendorPath($config['vendorPath']);
unset($config['vendorPath']);
} else {
// set "@vendor"
$this->getVendorPath();
}
if (isset($config['runtimePath'])) {
$this->setRuntimePath($config['runtimePath']);
unset($config['runtimePath']);
} else {
// set "@runtime"
$this->getRuntimePath();
}
if (isset($config['timeZone'])) {
$this->setTimeZone($config['timeZone']);
unset($config['timeZone']);
} elseif (!ini_get('date.timezone')) {
$this->setTimeZone('UTC');
}
13 years ago
}
14 years ago
13 years ago
/**
* Registers error handlers.
13 years ago
*/
public function registerErrorHandlers()
13 years ago
{
if (YII_ENABLE_ERROR_HANDLER) {
ini_set('display_errors', 0);
set_exception_handler(array($this, 'handleException'));
set_error_handler(array($this, 'handleError'), error_reporting());
12 years ago
// 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'));
}
14 years ago
}
/**
* Terminates the application.
13 years ago
* This method replaces PHP's exit() function by calling [[afterRequest()]] before exiting.
14 years ago
* @param integer $status exit status (value 0 means normal exit while other values mean abnormal exit).
13 years ago
* @param boolean $exit whether to exit the current request.
14 years ago
* It defaults to true, meaning the PHP's exit() function will be called at the end of this method.
*/
public function end($status = 0, $exit = true)
{
13 years ago
if (!$this->_ended) {
$this->_ended = true;
12 years ago
$this->getResponse()->end();
$this->afterRun();
13 years ago
}
if ($exit) {
exit($status);
}
}
/**
13 years ago
* 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()
{
$this->beforeRun();
12 years ago
$response = $this->getResponse();
$response->begin();
register_shutdown_function(array($this, 'end'), 0, false);
13 years ago
$status = $this->processRequest();
12 years ago
$response->end();
$this->afterRun();
13 years ago
return $status;
}
/**
* Raises the [[EVENT_BEFORE_RUN]] event right BEFORE the application processes the request.
14 years ago
*/
public function beforeRun()
14 years ago
{
$this->trigger(self::EVENT_BEFORE_RUN);
14 years ago
}
/**
* Raises the [[EVENT_AFTER_RUN]] event right AFTER the application processes the request.
13 years ago
*/
public function afterRun()
13 years ago
{
$this->trigger(self::EVENT_AFTER_RUN);
13 years ago
}
/**
* Processes the request.
13 years ago
* Child classes should override this method with actual request processing logic.
* @return integer the exit status of the controller action (0 means normal, non-zero values mean abnormal)
13 years ago
*/
public function processRequest()
{
return 0;
}
12 years ago
private $_runtimePath;
13 years ago
/**
14 years ago
* Returns the directory that stores runtime files.
* @return string the directory that stores runtime files.
* Defaults to the "runtime" subdirectory under [[basePath]].
14 years ago
*/
public function getRuntimePath()
{
12 years ago
if ($this->_runtimePath === null) {
14 years ago
$this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
}
return $this->_runtimePath;
14 years ago
}
/**
* Sets the directory that stores runtime files.
* @param string $path the directory that stores runtime files.
*/
public function setRuntimePath($path)
{
$this->_runtimePath = Yii::getAlias($path);
Yii::setAlias('@runtime', $this->_runtimePath);
14 years ago
}
12 years ago
private $_vendorPath;
/**
* Returns the directory that stores vendor files.
* @return string the directory that stores vendor files.
* Defaults to "vendor" directory under [[basePath]].
12 years ago
*/
public function getVendorPath()
{
12 years ago
if ($this->_vendorPath === null) {
12 years ago
$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)
{
12 years ago
$this->_vendorPath = Yii::getAlias($path);
Yii::setAlias('@vendor', $this->_vendorPath);
12 years ago
}
14 years ago
/**
* Returns the time zone used by this application.
* This is a simple wrapper of PHP function date_default_timezone_get().
* If time zone is not configured in php.ini or application config,
* it will be set to UTC by default.
14 years ago
* @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.
* @return \yii\db\Connection the database connection
14 years ago
*/
public function getDb()
{
return $this->getComponent('db');
}
/**
* Returns the error handler component.
13 years ago
* @return ErrorHandler the error handler application component.
14 years ago
*/
public function getErrorHandler()
{
return $this->getComponent('errorHandler');
}
/**
* Returns the cache component.
13 years ago
* @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
14 years ago
*/
public function getCache()
{
return $this->getComponent('cache');
}
/**
* Returns the formatter component.
* @return \yii\base\Formatter the formatter application component.
*/
public function getFormatter()
{
return $this->getComponent('formatter');
}
/**
14 years ago
* Returns the request component.
* @return \yii\web\Request|\yii\console\Request the request component
14 years ago
*/
public function getRequest()
{
return $this->getComponent('request');
}
/**
12 years ago
* Returns the response component.
* @return \yii\web\Response|\yii\console\Response the response component
*/
public function getResponse()
{
return $this->getComponent('response');
}
/**
12 years ago
* Returns the view object.
* @return View the view object that is used to render various view files.
12 years ago
*/
12 years ago
public function getView()
12 years ago
{
12 years ago
return $this->getComponent('view');
12 years ago
}
/**
* Returns the URL manager for this application.
* @return \yii\web\UrlManager the URL manager for this application.
*/
public function getUrlManager()
{
return $this->getComponent('urlManager');
}
/**
* Returns the internationalization (i18n) component
* @return \yii\i18n\I18N the internationalization component
*/
public function getI18N()
{
return $this->getComponent('i18n');
}
/**
* Returns the auth manager for this application.
* @return \yii\rbac\Manager the auth manager for this application.
12 years ago
*/
public function getAuthManager()
{
return $this->getComponent('authManager');
12 years ago
}
/**
14 years ago
* Registers the core application components.
* @see setComponents
*/
13 years ago
public function registerCoreComponents()
14 years ago
{
13 years ago
$this->setComponents(array(
'errorHandler' => array(
'class' => 'yii\base\ErrorHandler',
),
'formatter' => array(
'class' => 'yii\base\Formatter',
),
'i18n' => array(
'class' => 'yii\i18n\I18N',
14 years ago
),
'urlManager' => array(
'class' => 'yii\web\UrlManager',
14 years ago
),
12 years ago
'view' => array(
'class' => 'yii\base\View',
),
13 years ago
));
14 years ago
}
/**
* Handles uncaught PHP exceptions.
*
* This method is implemented as a PHP exception handler. It requires
* that constant YII_ENABLE_ERROR_HANDLER be defined true.
*
* @param \Exception $exception exception that is not caught
*/
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 {
$this->renderException($exception);
}
$this->end(1);
} catch (\Exception $e) {
// exception could be thrown in end() or ErrorHandler::handle()
$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);
}
}
/**
* 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
*
* @throws ErrorException
*/
public function handleError($code, $message, $file, $line)
{
if (error_reporting() !== 0) {
$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);
12 years ago
foreach ($trace as $frame) {
if ($frame['function'] == '__toString') {
$this->handleException($exception);
}
}
throw $exception;
}
}
/**
* Handles fatal PHP errors
*/
public function handleFatalError()
{
if (YII_ENABLE_ERROR_HANDLER) {
$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);
if (($handler = $this->getErrorHandler()) !== null) {
$handler->handle($exception);
} else {
$this->renderException($exception);
}
exit(1);
12 years ago
}
}
}
/**
* Renders an exception without using rich format.
* @param \Exception $exception the exception to be rendered.
*/
public function renderException($exception)
{
if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
$message = $exception->getName() . ': ' . $exception->getMessage();
} else {
$message = YII_DEBUG ? (string)$exception : 'Error: ' . $exception->getMessage();
}
if (PHP_SAPI) {
echo $message . "\n";
} else {
echo '<pre>' . htmlspecialchars($message, ENT_QUOTES, $this->charset) . '</pre>';
}
}
// todo: to be polished
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);
}
14 years ago
}