API Refactor AppKernel into CoreKernel

This commit is contained in:
Damian Mooyman 2017-06-20 16:39:43 +12:00
parent f7946aec33
commit d88d4ed4e4
14 changed files with 441 additions and 462 deletions

View File

@ -2,7 +2,7 @@
// CLI specific bootstrapping // CLI specific bootstrapping
use SilverStripe\Control\CLIRequestBuilder; use SilverStripe\Control\CLIRequestBuilder;
use SilverStripe\Core\AppKernel; use SilverStripe\Core\CoreKernel;
use SilverStripe\Core\HTTPApplication; use SilverStripe\Core\HTTPApplication;
require __DIR__ . '/src/includes/autoload.php'; require __DIR__ . '/src/includes/autoload.php';
@ -17,7 +17,7 @@ if (!in_array(PHP_SAPI, ["cli", "cgi", "cgi-fcgi"])) {
$request = CLIRequestBuilder::createFromEnvironment(); $request = CLIRequestBuilder::createFromEnvironment();
// Default application // Default application
$kernel = new AppKernel(BASE_PATH); $kernel = new CoreKernel(BASE_PATH);
$app = new HTTPApplication($kernel); $app = new HTTPApplication($kernel);
$response = $app->handle($request); $response = $app->handle($request);
$response->output(); $response->output();

View File

@ -19,16 +19,11 @@ resources are required temporarily. In general, we recommend running resource in
[command line](../cli), where configuration defaults for these settings are higher or even unlimited. [command line](../cli), where configuration defaults for these settings are higher or even unlimited.
<div class="info" markdown="1"> <div class="info" markdown="1">
SilverStripe can request more resources through `increase_memory_limit_to()` and `increase_time_limit_to()` functions. SilverStripe can request more resources through `Environment::increaseMemoryLimitTo()` and
`Environment::increaseTimeLimitTo()` functions.
</div> </div>
:::php :::php
function myBigFunction() { public function myBigFunction() {
increase_time_limit_to(400); Environment::increaseTimeLimitTo(400);
}
// or..
set_increase_time_limit_max();
// ..
}

View File

@ -1,7 +1,7 @@
<?php <?php
use SilverStripe\Control\HTTPRequestBuilder; use SilverStripe\Control\HTTPRequestBuilder;
use SilverStripe\Core\AppKernel; use SilverStripe\Core\CoreKernel;
use SilverStripe\Core\HTTPApplication; use SilverStripe\Core\HTTPApplication;
use SilverStripe\Core\Startup\ErrorControlChainMiddleware; use SilverStripe\Core\Startup\ErrorControlChainMiddleware;
@ -11,7 +11,7 @@ require __DIR__ . '/src/includes/autoload.php';
$request = HTTPRequestBuilder::createFromEnvironment(); $request = HTTPRequestBuilder::createFromEnvironment();
// Default application // Default application
$kernel = new AppKernel(BASE_PATH); $kernel = new CoreKernel(BASE_PATH);
$app = new HTTPApplication($kernel); $app = new HTTPApplication($kernel);
$app->addMiddleware(new ErrorControlChainMiddleware($app)); $app->addMiddleware(new ErrorControlChainMiddleware($app));
$response = $app->handle($request); $response = $app->handle($request);

View File

@ -1,428 +0,0 @@
<?php
namespace SilverStripe\Core;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
use SilverStripe\Config\Collections\CachedConfigCollection;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Core\Cache\ManifestCacheFactory;
use SilverStripe\Core\Config\ConfigLoader;
use SilverStripe\Core\Config\CoreConfigFactory;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Injector\InjectorLoader;
use SilverStripe\Core\Injector\SilverStripeServiceConfigurationLocator;
use SilverStripe\Core\Manifest\ClassLoader;
use SilverStripe\Core\Manifest\ClassManifest;
use SilverStripe\Core\Manifest\ModuleLoader;
use SilverStripe\Core\Manifest\ModuleManifest;
use SilverStripe\Dev\DebugView;
use SilverStripe\Dev\Install\DatabaseAdapterRegistry;
use SilverStripe\Logging\ErrorHandler;
use SilverStripe\ORM\DB;
use SilverStripe\View\ThemeManifest;
use SilverStripe\View\ThemeResourceLoader;
class AppKernel extends CoreKernel
{
protected $basePath = null;
/**
* Create a new kernel for this application
*
* @param string $basePath Path to base dir for this application
*/
public function __construct($basePath)
{
$this->basePath = $basePath;
// Initialise the dependency injector as soon as possible, as it is
// subsequently used by some of the following code
$injectorLoader = InjectorLoader::inst();
$injector = new Injector(array('locator' => SilverStripeServiceConfigurationLocator::class));
$injectorLoader->pushManifest($injector);
$this->setInjectorLoader($injectorLoader);
// Manifest cache factory
$manifestCacheFactory = $this->buildManifestCacheFactory();
// Class loader
$classLoader = ClassLoader::inst();
$classLoader->pushManifest(new ClassManifest($basePath, $manifestCacheFactory));
$this->setClassLoader($classLoader);
// Module loader
$moduleLoader = ModuleLoader::inst();
$moduleManifest = new ModuleManifest($basePath, $manifestCacheFactory);
$moduleLoader->pushManifest($moduleManifest);
$this->setModuleLoader($moduleLoader);
// Config loader
// @todo refactor CoreConfigFactory
$configFactory = new CoreConfigFactory($manifestCacheFactory);
$configManifest = $configFactory->createRoot();
$configLoader = ConfigLoader::inst();
$configLoader->pushManifest($configManifest);
$this->setConfigLoader($configLoader);
// Load template manifest
$themeResourceLoader = ThemeResourceLoader::inst();
$themeResourceLoader->addSet('$default', new ThemeManifest(
$basePath,
project(),
$manifestCacheFactory
));
$this->setThemeResourceLoader($themeResourceLoader);
}
public function getEnvironment()
{
// Check set
if ($this->enviroment) {
return $this->enviroment;
}
// Check saved session
$env = $this->sessionEnvironment();
if ($env) {
return $env;
}
// Check getenv
if ($env = getenv('SS_ENVIRONMENT_TYPE')) {
return $env;
}
return self::LIVE;
}
/**
* Check or update any temporary environment specified in the session.
*
* @return null|string
*/
protected function sessionEnvironment()
{
// Check isDev in querystring
if (isset($_GET['isDev'])) {
if (isset($_SESSION)) {
unset($_SESSION['isTest']); // In case we are changing from test mode
$_SESSION['isDev'] = $_GET['isDev'];
}
return self::DEV;
}
// Check isTest in querystring
if (isset($_GET['isTest'])) {
if (isset($_SESSION)) {
unset($_SESSION['isDev']); // In case we are changing from dev mode
$_SESSION['isTest'] = $_GET['isTest'];
}
return self::TEST;
}
// Check session
if (!empty($_SESSION['isDev'])) {
return self::DEV;
}
if (!empty($_SESSION['isTest'])) {
return self::TEST;
}
// no session environment
return null;
}
public function boot($flush = false)
{
$this->bootPHP();
$this->bootManifests($flush);
$this->bootErrorHandling();
$this->bootDatabase();
}
/**
* Configure database
*
* @throws HTTPResponse_Exception
*/
protected function bootDatabase()
{
// Check if a DB is named
$name = $this->getDatabaseName();
// Gracefully fail if no DB is configured
if (empty($name)) {
$this->detectLegacyEnvironment();
$this->redirectToInstaller();
}
// Set default database config
$databaseConfig = $this->getDatabaseConfig();
$databaseConfig['database'] = $this->getDatabaseName();
DB::setConfig($databaseConfig);
}
/**
* Check if there's a legacy _ss_environment.php file
*
* @throws HTTPResponse_Exception
*/
protected function detectLegacyEnvironment()
{
// Is there an _ss_environment.php file?
if (!file_exists($this->basePath . '/_ss_environment.php') &&
!file_exists(dirname($this->basePath) . '/_ss_environment.php')
) {
return;
}
// Build error response
$dv = new DebugView();
$body =
$dv->renderHeader() .
$dv->renderInfo(
"Configuraton Error",
Director::absoluteBaseURL()
) .
$dv->renderParagraph(
'You need to replace your _ss_environment.php file with a .env file, or with environment variables.<br><br>'
. 'See the <a href="https://docs.silverstripe.org/en/4/getting_started/environment_management/">'
. 'Environment Management</a> docs for more information.'
) .
$dv->renderFooter();
// Raise error
$response = new HTTPResponse($body, 500);
throw new HTTPResponse_Exception($response);
}
/**
* If missing configuration, redirect to install.php
*/
protected function redirectToInstaller()
{
// Error if installer not available
if (!file_exists($this->basePath . '/install.php')) {
throw new HTTPResponse_Exception(
'SilverStripe Framework requires a $databaseConfig defined.',
500
);
}
// Redirect to installer
$response = new HTTPResponse();
$response->redirect(Director::absoluteURL('install.php'));
throw new HTTPResponse_Exception($response);
}
/**
* Load database config from environment
*
* @return array
*/
protected function getDatabaseConfig()
{
// Check global config
global $databaseConfig;
if (!empty($databaseConfig)) {
return $databaseConfig;
}
/** @skipUpgrade */
$databaseConfig = [
"type" => getenv('SS_DATABASE_CLASS') ?: 'MySQLDatabase',
"server" => getenv('SS_DATABASE_SERVER') ?: 'localhost',
"username" => getenv('SS_DATABASE_USERNAME') ?: null,
"password" => getenv('SS_DATABASE_PASSWORD') ?: null,
];
// Set the port if called for
$dbPort = getenv('SS_DATABASE_PORT');
if ($dbPort) {
$databaseConfig['port'] = $dbPort;
}
// Set the timezone if called for
$dbTZ = getenv('SS_DATABASE_TIMEZONE');
if ($dbTZ) {
$databaseConfig['timezone'] = $dbTZ;
}
// For schema enabled drivers:
$dbSchema = getenv('SS_DATABASE_SCHEMA');
if ($dbSchema) {
$databaseConfig["schema"] = $dbSchema;
}
// For SQlite3 memory databases (mainly for testing purposes)
$dbMemory = getenv('SS_DATABASE_MEMORY');
if ($dbMemory) {
$databaseConfig["memory"] = $dbMemory;
}
// Allow database adapters to handle their own configuration
DatabaseAdapterRegistry::autoconfigure();
return $databaseConfig;
}
/**
* Get name of database
*
* @return string
*/
protected function getDatabaseName()
{
$prefix = getenv('SS_DATABASE_PREFIX') ?: 'SS_';
// Check globals
global $database;
if (!empty($database)) {
return $prefix.$database;
}
global $databaseConfig;
if (!empty($databaseConfig['database'])) {
return $databaseConfig['database']; // Note: Already includes prefix
}
// Check environment
$database = getenv('SS_DATABASE_NAME');
if ($database) {
return $prefix.$database;
}
// Auto-detect name
$chooseName = getenv('SS_DATABASE_CHOOSE_NAME');
if ($chooseName) {
// Find directory to build name from
$loopCount = (int)$chooseName;
$databaseDir = $this->basePath;
for ($i = 0; $i < $loopCount-1; $i++) {
$databaseDir = dirname($databaseDir);
}
// Build name
$database = str_replace('.', '', basename($databaseDir));
return $prefix.$database;
}
// no DB name (may be optional for some connectors)
return null;
}
/**
* Initialise PHP with default variables
*/
protected function bootPHP()
{
if ($this->getEnvironment() === self::LIVE) {
// limited to fatal errors and warnings in live mode
error_reporting(E_ALL & ~(E_DEPRECATED | E_STRICT | E_NOTICE));
} else {
// Report all errors in dev / test mode
error_reporting(E_ALL | E_STRICT);
}
global $_increase_time_limit_max;
$_increase_time_limit_max = -1;
/**
* Ensure we have enough memory
*/
Environment::increaseMemoryLimitTo('64M');
// Ensure we don't run into xdebug's fairly conservative infinite recursion protection limit
if (function_exists('xdebug_enable')) {
$current = ini_get('xdebug.max_nesting_level');
if ((int)$current < 200) {
ini_set('xdebug.max_nesting_level', 200);
}
}
/**
* Set default encoding
*/
mb_http_output('UTF-8');
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');
/**
* Enable better garbage collection
*/
gc_enable();
}
/**
* @return ManifestCacheFactory
*/
protected function buildManifestCacheFactory()
{
return new ManifestCacheFactory([
'namespace' => 'manifestcache',
'directory' => TempFolder::getTempFolder($this->basePath),
]);
}
/**
* @return bool
*/
protected function getIncludeTests()
{
return false;
}
/**
* Boot all manifests
*
* @param bool $flush
*/
protected function bootManifests($flush)
{
// Setup autoloader
$this->getClassLoader()->init($this->getIncludeTests(), $flush);
// Find modules
$this->getModuleLoader()->init($this->getIncludeTests(), $flush);
// Flush config
if ($flush) {
$config = $this->getConfigLoader()->getManifest();
if ($config instanceof CachedConfigCollection) {
$config->setFlush(true);
}
}
// After loading config, boot _config.php files
$this->getModuleLoader()->getManifest()->activateConfig();
// Find default templates
$defaultSet = $this->getThemeResourceLoader()->getSet('$default');
if ($defaultSet instanceof ThemeManifest) {
$defaultSet->init($this->getIncludeTests(), $flush);
}
}
/**
* Turn on error handling
*/
protected function bootErrorHandling()
{
// Register error handler
$errorHandler = Injector::inst()->get(ErrorHandler::class);
$errorHandler->start();
// Register error log file
$errorLog = getenv('SS_ERROR_LOG');
if ($errorLog) {
$logger = Injector::inst()->get(LoggerInterface::class);
if ($logger instanceof Logger) {
$logger->pushHandler(new StreamHandler($this->basePath . '/' . $errorLog, Logger::WARNING));
} else {
user_error("SS_ERROR_LOG setting only works with Monolog, you are using another logger", E_USER_WARNING);
}
}
}
}

View File

@ -3,11 +3,28 @@
namespace SilverStripe\Core; namespace SilverStripe\Core;
use InvalidArgumentException; use InvalidArgumentException;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
use SilverStripe\Config\Collections\CachedConfigCollection;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Core\Cache\ManifestCacheFactory;
use SilverStripe\Core\Config\ConfigLoader; use SilverStripe\Core\Config\ConfigLoader;
use SilverStripe\Core\Config\CoreConfigFactory;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Injector\InjectorLoader; use SilverStripe\Core\Injector\InjectorLoader;
use SilverStripe\Core\Injector\SilverStripeServiceConfigurationLocator;
use SilverStripe\Core\Manifest\ClassLoader; use SilverStripe\Core\Manifest\ClassLoader;
use SilverStripe\Core\Manifest\ClassManifest;
use SilverStripe\Core\Manifest\ModuleLoader; use SilverStripe\Core\Manifest\ModuleLoader;
use SilverStripe\Core\Manifest\ModuleManifest;
use SilverStripe\Dev\DebugView;
use SilverStripe\Dev\Install\DatabaseAdapterRegistry;
use SilverStripe\Logging\ErrorHandler;
use SilverStripe\ORM\DB;
use SilverStripe\View\ThemeManifest;
use SilverStripe\View\ThemeResourceLoader; use SilverStripe\View\ThemeResourceLoader;
/** /**
@ -55,8 +72,399 @@ class CoreKernel implements Kernel
*/ */
protected $themeResourceLoader = null; protected $themeResourceLoader = null;
protected $basePath = null;
/**
* Create a new kernel for this application
*
* @param string $basePath Path to base dir for this application
*/
public function __construct($basePath)
{
$this->basePath = $basePath;
// Initialise the dependency injector as soon as possible, as it is
// subsequently used by some of the following code
$injectorLoader = InjectorLoader::inst();
$injector = new Injector(array('locator' => SilverStripeServiceConfigurationLocator::class));
$injectorLoader->pushManifest($injector);
$this->setInjectorLoader($injectorLoader);
// Manifest cache factory
$manifestCacheFactory = $this->buildManifestCacheFactory();
// Class loader
$classLoader = ClassLoader::inst();
$classLoader->pushManifest(new ClassManifest($basePath, $manifestCacheFactory));
$this->setClassLoader($classLoader);
// Module loader
$moduleLoader = ModuleLoader::inst();
$moduleManifest = new ModuleManifest($basePath, $manifestCacheFactory);
$moduleLoader->pushManifest($moduleManifest);
$this->setModuleLoader($moduleLoader);
// Config loader
// @todo refactor CoreConfigFactory
$configFactory = new CoreConfigFactory($manifestCacheFactory);
$configManifest = $configFactory->createRoot();
$configLoader = ConfigLoader::inst();
$configLoader->pushManifest($configManifest);
$this->setConfigLoader($configLoader);
// Load template manifest
$themeResourceLoader = ThemeResourceLoader::inst();
$themeResourceLoader->addSet('$default', new ThemeManifest(
$basePath,
project(),
$manifestCacheFactory
));
$this->setThemeResourceLoader($themeResourceLoader);
}
public function getEnvironment()
{
// Check set
if ($this->enviroment) {
return $this->enviroment;
}
// Check saved session
$env = $this->sessionEnvironment();
if ($env) {
return $env;
}
// Check getenv
if ($env = getenv('SS_ENVIRONMENT_TYPE')) {
return $env;
}
return self::LIVE;
}
/**
* Check or update any temporary environment specified in the session.
*
* @return null|string
*/
protected function sessionEnvironment()
{
// Check isDev in querystring
if (isset($_GET['isDev'])) {
if (isset($_SESSION)) {
unset($_SESSION['isTest']); // In case we are changing from test mode
$_SESSION['isDev'] = $_GET['isDev'];
}
return self::DEV;
}
// Check isTest in querystring
if (isset($_GET['isTest'])) {
if (isset($_SESSION)) {
unset($_SESSION['isDev']); // In case we are changing from dev mode
$_SESSION['isTest'] = $_GET['isTest'];
}
return self::TEST;
}
// Check session
if (!empty($_SESSION['isDev'])) {
return self::DEV;
}
if (!empty($_SESSION['isTest'])) {
return self::TEST;
}
// no session environment
return null;
}
public function boot($flush = false) public function boot($flush = false)
{ {
$this->bootPHP();
$this->bootManifests($flush);
$this->bootErrorHandling();
$this->bootDatabase();
}
/**
* Configure database
*
* @throws HTTPResponse_Exception
*/
protected function bootDatabase()
{
// Check if a DB is named
$name = $this->getDatabaseName();
// Gracefully fail if no DB is configured
if (empty($name)) {
$this->detectLegacyEnvironment();
$this->redirectToInstaller();
}
// Set default database config
$databaseConfig = $this->getDatabaseConfig();
$databaseConfig['database'] = $this->getDatabaseName();
DB::setConfig($databaseConfig);
}
/**
* Check if there's a legacy _ss_environment.php file
*
* @throws HTTPResponse_Exception
*/
protected function detectLegacyEnvironment()
{
// Is there an _ss_environment.php file?
if (!file_exists($this->basePath . '/_ss_environment.php') &&
!file_exists(dirname($this->basePath) . '/_ss_environment.php')
) {
return;
}
// Build error response
$dv = new DebugView();
$body =
$dv->renderHeader() .
$dv->renderInfo(
"Configuraton Error",
Director::absoluteBaseURL()
) .
$dv->renderParagraph(
'You need to replace your _ss_environment.php file with a .env file, or with environment variables.<br><br>'
. 'See the <a href="https://docs.silverstripe.org/en/4/getting_started/environment_management/">'
. 'Environment Management</a> docs for more information.'
) .
$dv->renderFooter();
// Raise error
$response = new HTTPResponse($body, 500);
throw new HTTPResponse_Exception($response);
}
/**
* If missing configuration, redirect to install.php
*/
protected function redirectToInstaller()
{
// Error if installer not available
if (!file_exists($this->basePath . '/install.php')) {
throw new HTTPResponse_Exception(
'SilverStripe Framework requires a $databaseConfig defined.',
500
);
}
// Redirect to installer
$response = new HTTPResponse();
$response->redirect(Director::absoluteURL('install.php'));
throw new HTTPResponse_Exception($response);
}
/**
* Load database config from environment
*
* @return array
*/
protected function getDatabaseConfig()
{
// Check global config
global $databaseConfig;
if (!empty($databaseConfig)) {
return $databaseConfig;
}
/** @skipUpgrade */
$databaseConfig = [
"type" => getenv('SS_DATABASE_CLASS') ?: 'MySQLDatabase',
"server" => getenv('SS_DATABASE_SERVER') ?: 'localhost',
"username" => getenv('SS_DATABASE_USERNAME') ?: null,
"password" => getenv('SS_DATABASE_PASSWORD') ?: null,
];
// Set the port if called for
$dbPort = getenv('SS_DATABASE_PORT');
if ($dbPort) {
$databaseConfig['port'] = $dbPort;
}
// Set the timezone if called for
$dbTZ = getenv('SS_DATABASE_TIMEZONE');
if ($dbTZ) {
$databaseConfig['timezone'] = $dbTZ;
}
// For schema enabled drivers:
$dbSchema = getenv('SS_DATABASE_SCHEMA');
if ($dbSchema) {
$databaseConfig["schema"] = $dbSchema;
}
// For SQlite3 memory databases (mainly for testing purposes)
$dbMemory = getenv('SS_DATABASE_MEMORY');
if ($dbMemory) {
$databaseConfig["memory"] = $dbMemory;
}
// Allow database adapters to handle their own configuration
DatabaseAdapterRegistry::autoconfigure();
return $databaseConfig;
}
/**
* Get name of database
*
* @return string
*/
protected function getDatabaseName()
{
$prefix = getenv('SS_DATABASE_PREFIX') ?: 'SS_';
// Check globals
global $database;
if (!empty($database)) {
return $prefix.$database;
}
global $databaseConfig;
if (!empty($databaseConfig['database'])) {
return $databaseConfig['database']; // Note: Already includes prefix
}
// Check environment
$database = getenv('SS_DATABASE_NAME');
if ($database) {
return $prefix.$database;
}
// Auto-detect name
$chooseName = getenv('SS_DATABASE_CHOOSE_NAME');
if ($chooseName) {
// Find directory to build name from
$loopCount = (int)$chooseName;
$databaseDir = $this->basePath;
for ($i = 0; $i < $loopCount-1; $i++) {
$databaseDir = dirname($databaseDir);
}
// Build name
$database = str_replace('.', '', basename($databaseDir));
return $prefix.$database;
}
// no DB name (may be optional for some connectors)
return null;
}
/**
* Initialise PHP with default variables
*/
protected function bootPHP()
{
if ($this->getEnvironment() === self::LIVE) {
// limited to fatal errors and warnings in live mode
error_reporting(E_ALL & ~(E_DEPRECATED | E_STRICT | E_NOTICE));
} else {
// Report all errors in dev / test mode
error_reporting(E_ALL | E_STRICT);
}
/**
* Ensure we have enough memory
*/
Environment::increaseMemoryLimitTo('64M');
// Ensure we don't run into xdebug's fairly conservative infinite recursion protection limit
if (function_exists('xdebug_enable')) {
$current = ini_get('xdebug.max_nesting_level');
if ((int)$current < 200) {
ini_set('xdebug.max_nesting_level', 200);
}
}
/**
* Set default encoding
*/
mb_http_output('UTF-8');
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');
/**
* Enable better garbage collection
*/
gc_enable();
}
/**
* @return ManifestCacheFactory
*/
protected function buildManifestCacheFactory()
{
return new ManifestCacheFactory([
'namespace' => 'manifestcache',
'directory' => TempFolder::getTempFolder($this->basePath),
]);
}
/**
* @return bool
*/
protected function getIncludeTests()
{
return false;
}
/**
* Boot all manifests
*
* @param bool $flush
*/
protected function bootManifests($flush)
{
// Setup autoloader
$this->getClassLoader()->init($this->getIncludeTests(), $flush);
// Find modules
$this->getModuleLoader()->init($this->getIncludeTests(), $flush);
// Flush config
if ($flush) {
$config = $this->getConfigLoader()->getManifest();
if ($config instanceof CachedConfigCollection) {
$config->setFlush(true);
}
}
// After loading config, boot _config.php files
$this->getModuleLoader()->getManifest()->activateConfig();
// Find default templates
$defaultSet = $this->getThemeResourceLoader()->getSet('$default');
if ($defaultSet instanceof ThemeManifest) {
$defaultSet->init($this->getIncludeTests(), $flush);
}
}
/**
* Turn on error handling
*/
protected function bootErrorHandling()
{
// Register error handler
$errorHandler = Injector::inst()->get(ErrorHandler::class);
$errorHandler->start();
// Register error log file
$errorLog = getenv('SS_ERROR_LOG');
if ($errorLog) {
$logger = Injector::inst()->get(LoggerInterface::class);
if ($logger instanceof Logger) {
$logger->pushHandler(new StreamHandler($this->basePath . '/' . $errorLog, Logger::WARNING));
} else {
user_error("SS_ERROR_LOG setting only works with Monolog, you are using another logger", E_USER_WARNING);
}
}
} }
public function shutdown() public function shutdown()
@ -130,11 +538,6 @@ class CoreKernel implements Kernel
return $this; return $this;
} }
public function getEnvironment()
{
return $this->enviroment ?: self::LIVE;
}
public function setEnvironment($environment) public function setEnvironment($environment)
{ {
if (!in_array($environment, [self::DEV, self::TEST, self::LIVE, null])) { if (!in_array($environment, [self::DEV, self::TEST, self::LIVE, null])) {

View File

@ -48,7 +48,7 @@ class Environment
/** /**
* Increase the memory limit to the given level if it's currently too low. * Increase the memory limit to the given level if it's currently too low.
* Only increases up to the maximum defined in {@link set_increase_memory_limit_max()}, * Only increases up to the maximum defined in {@link setMemoryLimitMax()},
* and defaults to the 'memory_limit' setting in the PHP configuration. * and defaults to the 'memory_limit' setting in the PHP configuration.
* *
* @param string|float|int $memoryLimit A memory limit string, such as "64M". If omitted, unlimited memory will be set. * @param string|float|int $memoryLimit A memory limit string, such as "64M". If omitted, unlimited memory will be set.
@ -81,7 +81,7 @@ class Environment
} }
/** /**
* Set the maximum allowed value for {@link increase_memory_limit_to()}. * Set the maximum allowed value for {@link increaseMemoryLimitTo()}.
* The same result can also be achieved through 'suhosin.memory_limit' * The same result can also be achieved through 'suhosin.memory_limit'
* if PHP is running with the Suhosin system. * if PHP is running with the Suhosin system.
* *
@ -109,7 +109,7 @@ class Environment
/** /**
* Increase the time limit of this script. By default, the time will be unlimited. * Increase the time limit of this script. By default, the time will be unlimited.
* Only works if 'safe_mode' is off in the PHP configuration. * Only works if 'safe_mode' is off in the PHP configuration.
* Only values up to {@link get_increase_time_limit_max()} are allowed. * Only values up to {@link getTimeLimitMax()} are allowed.
* *
* @param int $timeLimit The time limit in seconds. If omitted, no time limit will be set. * @param int $timeLimit The time limit in seconds. If omitted, no time limit will be set.
* @return Boolean TRUE indicates a successful change, FALSE a denied change. * @return Boolean TRUE indicates a successful change, FALSE a denied change.
@ -135,7 +135,7 @@ class Environment
} }
/** /**
* Set the maximum allowed value for {@link increase_timeLimit_to()}; * Set the maximum allowed value for {@link increaseTimeLimitTo()};
* *
* @param int $timeLimit Limit in seconds * @param int $timeLimit Limit in seconds
*/ */

View File

@ -2,6 +2,7 @@
namespace SilverStripe\Dev; namespace SilverStripe\Dev;
use SilverStripe\Core\Environment;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\View\ViewableData; use SilverStripe\View\ViewableData;
@ -142,8 +143,8 @@ abstract class BulkLoader extends ViewableData
*/ */
public function load($filepath) public function load($filepath)
{ {
increase_time_limit_to(3600); Environment::increaseTimeLimitTo(3600);
increase_memory_limit_to('512M'); Environment::increaseMemoryLimitTo('512M');
//get all instances of the to be imported data object //get all instances of the to be imported data object
if ($this->deleteExistingRecords) { if ($this->deleteExistingRecords) {

View File

@ -5,7 +5,7 @@ namespace SilverStripe\Dev\Install;
use Exception; use Exception;
use SilverStripe\Control\HTTPRequest; use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\Session; use SilverStripe\Control\Session;
use SilverStripe\Core\AppKernel; use SilverStripe\Core\CoreKernel;
use SilverStripe\Core\HTTPApplication; use SilverStripe\Core\HTTPApplication;
use SilverStripe\Core\Kernel; use SilverStripe\Core\Kernel;
use SilverStripe\Core\Startup\ParameterConfirmationToken; use SilverStripe\Core\Startup\ParameterConfirmationToken;
@ -215,7 +215,7 @@ PHP
$request->setSession($session); $request->setSession($session);
// Install kernel (fix to dev) // Install kernel (fix to dev)
$kernel = new AppKernel(BASE_PATH); $kernel = new CoreKernel(BASE_PATH);
$kernel->setEnvironment(Kernel::DEV); $kernel->setEnvironment(Kernel::DEV);
$app = new HTTPApplication($kernel); $app = new HTTPApplication($kernel);

View File

@ -19,7 +19,7 @@ use SilverStripe\Core\HTTPApplication;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Injector\InjectorLoader; use SilverStripe\Core\Injector\InjectorLoader;
use SilverStripe\Core\Manifest\ClassLoader; use SilverStripe\Core\Manifest\ClassLoader;
use SilverStripe\Core\TestKernel; use SilverStripe\Dev\TestKernel;
use SilverStripe\Dev\State\SapphireTestState; use SilverStripe\Dev\State\SapphireTestState;
use SilverStripe\Dev\State\TestState; use SilverStripe\Dev\State\TestState;
use SilverStripe\i18n\i18n; use SilverStripe\i18n\i18n;

View File

@ -4,7 +4,7 @@ namespace SilverStripe\Dev\State;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Kernel; use SilverStripe\Core\Kernel;
use SilverStripe\Core\TestKernel; use SilverStripe\Dev\TestKernel;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
/** /**
@ -22,7 +22,7 @@ class KernelTestState implements TestState
/** /**
* Get active Kernel instance * Get active Kernel instance
* *
* @return TestKernel * @return \SilverStripe\Dev\TestKernel
*/ */
protected function kernel() protected function kernel()
{ {

View File

@ -3,6 +3,7 @@
namespace SilverStripe\Dev\Tasks; namespace SilverStripe\Dev\Tasks;
use SilverStripe\Control\HTTPRequest; use SilverStripe\Control\HTTPRequest;
use SilverStripe\Core\Environment;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\Debug; use SilverStripe\Dev\Debug;
use SilverStripe\Dev\BuildTask; use SilverStripe\Dev\BuildTask;
@ -40,7 +41,7 @@ class i18nTextCollectorTask extends BuildTask
*/ */
public function run($request) public function run($request)
{ {
increase_time_limit_to(); Environment::increaseTimeLimitTo();
$collector = i18nTextCollector::create($request->getVar('locale')); $collector = i18nTextCollector::create($request->getVar('locale'));
$merge = $this->getIsMerge($request); $merge = $this->getIsMerge($request);

View File

@ -1,11 +1,13 @@
<?php <?php
namespace SilverStripe\Core; namespace SilverStripe\Dev;
use SilverStripe\Core\CoreKernel;
/** /**
* Kernel for running unit tests * Kernel for running unit tests
*/ */
class TestKernel extends AppKernel class TestKernel extends CoreKernel
{ {
public function __construct($basePath) public function __construct($basePath)
{ {

View File

@ -5,6 +5,7 @@ namespace SilverStripe\ORM;
use SilverStripe\Control\Director; use SilverStripe\Control\Director;
use SilverStripe\Control\Controller; use SilverStripe\Control\Controller;
use SilverStripe\Core\ClassInfo; use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Environment;
use SilverStripe\Core\Manifest\ClassLoader; use SilverStripe\Core\Manifest\ClassLoader;
use SilverStripe\Dev\DevelopmentAdmin; use SilverStripe\Dev\DevelopmentAdmin;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
@ -119,7 +120,7 @@ class DatabaseAdmin extends Controller
public function build() public function build()
{ {
// The default time limit of 30 seconds is normally not enough // The default time limit of 30 seconds is normally not enough
increase_time_limit_to(600); Environment::increaseTimeLimitTo(600);
// Get all our classes // Get all our classes
ClassLoader::inst()->getManifest()->regenerate(false); ClassLoader::inst()->getManifest()->regenerate(false);

View File

@ -36,6 +36,10 @@ function singleton($className)
function project() function project()
{ {
global $project; global $project;
// Set default project
if (empty($project) && file_exists(BASE_PATH . '/mysite')) {
$project = 'mysite';
}
return $project; return $project;
} }