Commit 761ac679 authored by catch's avatar catch

Issue #1849004 by chx, xjm: One Service Container To Rule Them All.

parent aa676a59
<?php
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Database\Database;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Symfony\Component\ClassLoader\UniversalClassLoader;
......@@ -128,39 +129,44 @@
const DRUPAL_BOOTSTRAP_CONFIGURATION = 0;
/**
* Second bootstrap phase: try to serve a cached page.
* Second bootstrap phase, initalize a kernel.
*/
const DRUPAL_BOOTSTRAP_PAGE_CACHE = 1;
const DRUPAL_BOOTSTRAP_KERNEL = 1;
/**
* Third bootstrap phase: initialize database layer.
* Third bootstrap phase: try to serve a cached page.
*/
const DRUPAL_BOOTSTRAP_DATABASE = 2;
const DRUPAL_BOOTSTRAP_PAGE_CACHE = 2;
/**
* Fourth bootstrap phase: initialize the variable system.
* Fourth bootstrap phase: initialize database layer.
*/
const DRUPAL_BOOTSTRAP_VARIABLES = 3;
const DRUPAL_BOOTSTRAP_DATABASE = 3;
/**
* Fifth bootstrap phase: initialize session handling.
* Fifth bootstrap phase: initialize the variable system.
*/
const DRUPAL_BOOTSTRAP_SESSION = 4;
const DRUPAL_BOOTSTRAP_VARIABLES = 4;
/**
* Sixth bootstrap phase: set up the page header.
* Sixth bootstrap phase: initialize session handling.
*/
const DRUPAL_BOOTSTRAP_PAGE_HEADER = 5;
const DRUPAL_BOOTSTRAP_SESSION = 5;
/**
* Seventh bootstrap phase: load code for subsystems and modules.
* Seventh bootstrap phase: set up the page header.
*/
const DRUPAL_BOOTSTRAP_CODE = 6;
const DRUPAL_BOOTSTRAP_PAGE_HEADER = 6;
/**
* Eighth bootstrap phase: load code for subsystems and modules.
*/
const DRUPAL_BOOTSTRAP_CODE = 7;
/**
* Final bootstrap phase: initialize language, path, theme, and modules.
*/
const DRUPAL_BOOTSTRAP_FULL = 7;
const DRUPAL_BOOTSTRAP_FULL = 8;
/**
* Role ID for anonymous users; should match what's in the "role" table.
......@@ -2105,6 +2111,7 @@ function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
// Not drupal_static(), because does not depend on any run-time information.
static $phases = array(
DRUPAL_BOOTSTRAP_CONFIGURATION,
DRUPAL_BOOTSTRAP_KERNEL,
DRUPAL_BOOTSTRAP_PAGE_CACHE,
DRUPAL_BOOTSTRAP_DATABASE,
DRUPAL_BOOTSTRAP_VARIABLES,
......@@ -2115,14 +2122,15 @@ function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
);
// Not drupal_static(), because the only legitimate API to control this is to
// call drupal_bootstrap() with a new phase parameter.
static $final_phase;
static $final_phase = -1;
// Not drupal_static(), because it's impossible to roll back to an earlier
// bootstrap state.
static $stored_phase = -1;
// When not recursing, store the phase name so it's not forgotten while
// recursing.
if ($new_phase) {
// When not recursing, store the phase name so it's not forgotten during
// recursion. Additionally, ensure that $final_phase is never rolled back to an
// earlier bootstrap state.
if ($new_phase && $phase > $final_phase) {
$final_phase = $phase;
}
if (isset($phase)) {
......@@ -2142,6 +2150,10 @@ function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
_drupal_bootstrap_configuration();
break;
case DRUPAL_BOOTSTRAP_KERNEL:
_drupal_bootstrap_kernel();
break;
case DRUPAL_BOOTSTRAP_PAGE_CACHE:
_drupal_bootstrap_page_cache();
break;
......@@ -2274,6 +2286,18 @@ function _drupal_bootstrap_configuration() {
}
}
/**
* Initialize the kernel / service container.
*/
function _drupal_bootstrap_kernel() {
// Normally, index.php puts a container in drupal_container() by creating a
// kernel. If there is no container yet, create one.
if (!drupal_container()) {
$kernel = new DrupalKernel('prod', FALSE, drupal_classloader());
$kernel->boot();
}
}
/**
* Attempts to serve a page from the cache.
*/
......@@ -2410,91 +2434,28 @@ function drupal_get_bootstrap_phase() {
/**
* Retrieves the Drupal Container to standardize object construction.
*
* On a normal page request the container is built by the kernel and passed in
* to this function which stores it statically. Any full bootstrap outside of
* the context of a page request will require a container with a minimal set of
* services. If this function is called without the $rebuild parameter, and no
* container object has been statically cached, it builds this minimal container,
* registering the services that are required.
* The container is built by the kernel and passed in to this function which
* stores it statically. The container always contains the services from
* \Drupal\Core\CoreBundle, the bundles of enabled modules and any other
* bundles defined in $GLOBALS['conf']['container_bundles'].
*
* @see Drupal\Core\DrupalKernel
*
* @param Symfony\Component\DependencyInjection\Container $new_container
* A new container instance to replace the current.
* @param bool $rebuild
* (optional) Internal use only. Whether to enforce a rebuild of the container.
* Used by the testing framework to inject a fresh container for unit tests.
* (optional) A new container instance to replace the current.
*
* @return Symfony\Component\DependencyInjection\Container
* @return Symfony\Component\DependencyInjection\Container|bool
* The instance of the Container used to set up and maintain object
* instances.
* instances or FALSE if none exist yet.
*/
function drupal_container(Container $new_container = NULL, $rebuild = FALSE) {
function drupal_container(Container $new_container = NULL) {
// We do not use drupal_static() here because we do not have a mechanism by
// which to reinitialize the stored objects, so a drupal_static_reset() call
// would leave Drupal in a nonfunctional state.
static $container = NULL;
if ($rebuild) {
$container = NULL;
}
static $container;
if (isset($new_container)) {
$container = $new_container;
}
if (!isset($container)) {
// This is only ever used by the installer and by run-tests.sh.
// @todo Remove this entire section once these have been converted to use a
// kernel.
$container = new ContainerBuilder();
// Register active configuration storage.
$container
->register('config.cachedstorage.storage', 'Drupal\Core\Config\FileStorage')
->addArgument(config_get_config_directory(CONFIG_ACTIVE_DIRECTORY));
// @todo Replace this with a cache.factory service plus 'config' argument.
$container
->register('cache.config', 'Drupal\Core\Cache\CacheBackendInterface')
->setFactoryClass('Drupal\Core\Cache\CacheFactory')
->setFactoryMethod('get')
->addArgument('config');
$container
->register('config.storage', 'Drupal\Core\Config\CachedStorage')
->addArgument(new Reference('config.cachedstorage.storage'))
->addArgument(new Reference('cache.config'));
// Register configuration object factory.
$container->register('config.subscriber.globalconf', 'Drupal\Core\EventSubscriber\ConfigGlobalOverrideSubscriber');
$container->register('dispatcher', 'Symfony\Component\EventDispatcher\EventDispatcher')
->addMethodCall('addSubscriber', array(new Reference('config.subscriber.globalconf')));
$container->register('config.factory', 'Drupal\Core\Config\ConfigFactory')
->addArgument(new Reference('config.storage'))
->addArgument(new Reference('dispatcher'));
// Register staging configuration storage.
$container
->register('config.storage.staging', 'Drupal\Core\Config\FileStorage')
->addArgument(config_get_config_directory(CONFIG_STAGING_DIRECTORY));
// Register the service for the default database connection.
$container->register('database', 'Drupal\Core\Database\Connection')
->setFactoryClass('Drupal\Core\Database\Database')
->setFactoryMethod('getConnection')
->addArgument('default');
// Register the KeyValueStore factory.
$container
->register('keyvalue', 'Drupal\Core\KeyValueStore\KeyValueFactory')
->addArgument(new Reference('service_container'));
$container
->register('keyvalue.database', 'Drupal\Core\KeyValueStore\KeyValueDatabaseFactory')
->addArgument(new Reference('database'));
$container->register('path.alias_manager', 'Drupal\Core\Path\AliasManager')
->addArgument(new Reference('database'))
->addArgument(new Reference('keyvalue'));
// Register the EntityManager.
$container->register('plugin.manager.entity', 'Drupal\Core\Entity\EntityManager');
}
return $container;
}
......
......@@ -5,10 +5,12 @@
* API for handling file uploads and server file management.
*/
use Drupal\Core\StreamWrapper\LocalStream;
use Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Drupal\Core\StreamWrapper\LocalStream;
/**
* Stream wrapper bit flags that are the basis for composite types.
*
......@@ -558,7 +560,7 @@ function file_save_htaccess($directory, $private = TRUE) {
if ($private) {
// Private .htaccess file.
$htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nDeny from all\nOptions None\nOptions +FollowSymLinks";
$htaccess_lines = MTimeProtectedFastFileStorage::HTACCESS;
}
else {
// Public .htaccess file.
......
......@@ -288,6 +288,9 @@ function install_begin_request(&$install_state) {
// Determine whether the configuration system is ready to operate.
$install_state['config_verified'] = install_verify_config_directory(CONFIG_ACTIVE_DIRECTORY) && install_verify_config_directory(CONFIG_STAGING_DIRECTORY);
// Check existing settings.php.
$install_state['database_verified'] = install_verify_database_settings();
$install_state['settings_verified'] = $install_state['config_verified'] && $install_state['database_verified'];
// If it is not, replace the configuration storage with the InstallStorage
// implementation, for the following reasons:
......@@ -309,10 +312,15 @@ function install_begin_request(&$install_state) {
// the default configuration provided by the installation profile and
// modules (most notably System module). The InstallStorage therefore reads
// from the default configuration directories of extensions.
// This override is reverted as soon as the config directory has been set up
// successfully.
// This override is reverted as soon as the config directory and the
// database has been set up successfully.
// @see drupal_install_config_directories()
if (!$install_state['config_verified']) {
// @see install_settings_form_submit()
if ($install_state['settings_verified']) {
$kernel = new DrupalKernel('install', FALSE, drupal_classloader(), FALSE);
$kernel->boot();
}
else {
// @todo Move into a proper Drupal\Core\DependencyInjection\InstallContainerBuilder.
$container = new ContainerBuilder();
......@@ -362,10 +370,6 @@ function install_begin_request(&$install_state) {
// accessing the database before it is set up yet.)
drupal_maintenance_theme();
// Check existing settings.php.
$install_state['database_verified'] = install_verify_database_settings();
$install_state['settings_verified'] = $install_state['config_verified'] && $install_state['database_verified'];
if ($install_state['database_verified']) {
// Initialize the database system. Note that the connection
// won't be initialized until it is actually requested.
......@@ -1104,11 +1108,6 @@ function install_settings_form_submit($form, &$form_state) {
// Add the config directories to settings.php.
drupal_install_config_directories();
// We have valid configuration directories in settings.php.
// Reset the service container, so the config.storage service will use the
// actual active storage for installing configuration.
drupal_container(NULL, TRUE);
// Indicate that the settings file has been verified, and check the database
// for the last completed task, now that we have a valid connection. This
// last step is important since we want to trigger an error if the new
......@@ -1500,10 +1499,6 @@ function install_bootstrap_full(&$install_state) {
// Clear the module list that was overriden earlier in the process.
// This will allow all freshly installed modules to be loaded.
module_list_reset();
// Instantiate the kernel.
$kernel = new DrupalKernel('prod', FALSE, drupal_classloader(), FALSE);
$kernel->boot();
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
}
......
......@@ -6,6 +6,7 @@
*/
use Drupal\Core\Database\Database;
use Drupal\Core\DrupalKernel;
use Drupal\locale\Gettext;
/**
......@@ -421,6 +422,9 @@ function drupal_verify_profile($install_state) {
function drupal_install_system() {
// Create tables.
drupal_install_schema('system');
// Immediately boot a kernel to have real services ready.
$kernel = new DrupalKernel('install', FALSE, drupal_classloader(), FALSE);
$kernel->boot();
$system_path = drupal_get_path('module', 'system');
require_once DRUPAL_ROOT . '/' . $system_path . '/system.install';
......
......@@ -83,6 +83,10 @@ function writeable() {
* Implements Drupal\Component\PhpStorage\PhpStorageInterface::deleteAll().
*/
function deleteAll() {
// @todo remove this to properly decouple this class from Drupal.
if (!function_exists('file_unmanaged_delete_recursive')) {
include_once DRUPAL_ROOT . '/core/includes/file.inc';
}
return file_unmanaged_delete_recursive($this->directory, array(__CLASS__, 'filePreDeleteCallback'));
}
......
......@@ -40,6 +40,8 @@
*/
class MTimeProtectedFastFileStorage extends FileStorage {
const HTACCESS="SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nDeny from all\nOptions None\nOptions +FollowSymLinks";
/**
* The secret used in the HMAC.
*
......@@ -144,7 +146,10 @@ protected function ensureDirectory() {
mkdir($this->directory, 0700, TRUE);
}
chmod($this->directory, 0700);
file_save_htaccess($this->directory);
$htaccess_path = $this->directory . '/.htaccess';
if (!file_exists($htaccess_path) && file_put_contents($htaccess_path, self::HTACCESS)) {
@chmod($htaccess_path, 0444);
}
}
/**
......
......@@ -158,11 +158,6 @@ public function boot() {
}
$this->initializeContainer();
$this->booted = TRUE;
// @todo Remove this once everything in the bootstrap has been converted to
// services in the DIC.
drupal_bootstrap(DRUPAL_BOOTSTRAP_CODE);
// Now that full bootstrap is complete, we can dump the container if it
// was just rebuilt.
if ($this->containerNeedsDumping && !$this->dumpDrupalContainer($this->container, $this->getContainerBaseClass())) {
watchdog('DrupalKernel', 'Container cannot be written to disk');
}
......
......@@ -8,6 +8,7 @@
namespace Drupal\simpletest;
use Drupal\Core\DrupalKernel;
use Symfony\Component\DependencyInjection\Reference;
use Drupal\Core\Database\Database;
use Symfony\Component\DependencyInjection\ContainerInterface;
......@@ -129,6 +130,21 @@ public function containerBuild($container) {
$conf['keyvalue_default'] = 'keyvalue.memory';
$container
->register('keyvalue.memory', 'Drupal\Core\KeyValueStore\KeyValueMemoryFactory');
if (!$container->has('keyvalue')) {
// TestBase::setUp puts a completely empty container in
// drupal_container() which is somewhat the mirror of the empty
// environment being set up. Unit tests need not to waste time with
// getting a container set up for them. Drupal Unit Tests might just get
// away with a simple container holding the absolute bare minimum. When
// a kernel is overridden then there's no need to re-register the keyvalue
// service but when a test is happy with the superminimal container put
// together here, it still might a keyvalue storage for anything (for
// eg. module_enable) using state() -- that's why a memory service was
// added in the first place.
$container
->register('keyvalue', 'Drupal\Core\KeyValueStore\KeyValueFactory')
->addArgument(new Reference('service_container'));
}
}
/**
......
......@@ -8,6 +8,7 @@
namespace Drupal\simpletest;
use Drupal\Core\Database\Database;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Database\ConnectionNotDefinedException;
use Drupal\Core\DrupalKernel;
use ReflectionMethod;
......@@ -819,7 +820,9 @@ protected function prepareEnvironment() {
$this->originalContainer = clone drupal_container();
$this->originalLanguage = $language_interface;
$this->originalConfigDirectories = $GLOBALS['config_directories'];
$this->originalThemeKey = isset($GLOBALS['theme_key']) ? $GLOBALS['theme_key'] : NULL;
if (isset($GLOBALS['theme_key'])) {
$this->originalThemeKey = $GLOBALS['theme_key'];
}
$this->originalTheme = isset($GLOBALS['theme']) ? $GLOBALS['theme'] : NULL;
// Save further contextual information.
......@@ -873,7 +876,8 @@ protected function prepareEnvironment() {
}
// Reset and create a new service container.
$this->container = drupal_container(NULL, TRUE);
$this->container = new ContainerBuilder();
drupal_container($this->container);
// Unset globals.
unset($GLOBALS['theme_key']);
......@@ -906,9 +910,6 @@ protected function prepareEnvironment() {
* enabled modules to be immediately available in the same request.
*/
protected function rebuildContainer() {
// DrupalKernel expects to merge a fresh bootstrap container, not remerge
// what is left over from a prior container build.
drupal_container(NULL, TRUE);
// Create a new DrupalKernel for testing purposes, now that all required
// modules have been enabled. This also stores a new dependency injection
// container in drupal_container(). Drupal\simpletest\TestBase::tearDown()
......@@ -966,11 +967,13 @@ protected function tearDown() {
// In case a fatal error occurred that was not in the test process read the
// log to pick up any fatal errors.
simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE);
$captured_emails = state()->get('system.test_email_collector') ?: array();
$emailCount = count($captured_emails);
if ($emailCount) {
$message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
$this->pass($message, t('E-mail'));
if (($container = drupal_container()) && $container->has('keyvalue')) {
$captured_emails = state()->get('system.test_email_collector') ?: array();
$emailCount = count($captured_emails);
if ($emailCount) {
$message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
$this->pass($message, t('E-mail'));
}
}
// Delete temporary files directory.
......@@ -985,7 +988,9 @@ protected function tearDown() {
$databases['default']['default'] = $connection_info['default'];
// Restore original globals.
$GLOBALS['theme_key'] = $this->originalThemeKey;
if (isset($this->originalThemeKey)) {
$GLOBALS['theme_key'] = $this->originalThemeKey;
}
$GLOBALS['theme'] = $this->originalTheme;
// Reset all static variables.
......
......@@ -22,24 +22,13 @@ public static function getInfo() {
);
}
function setUp() {
parent::setUp();
// Remove the keyvalue service definition, since this test wants to verify
// the filesystem scan fallback of drupal_get_filename().
$this->keyvalue_definition = $this->container->getDefinition('keyvalue');
$this->container->removeDefinition('keyvalue');
}
function tearDown() {
$this->container->setDefinition('keyvalue', $this->keyvalue_definition);
parent::tearDown();
}
/**
* Tests that drupal_get_filename() works when the file is not in database.
*/
function testDrupalGetFilename() {
// Assert that the test is meaningful by making sure the keyvalue service
// does not exist.
$this->assertFalse(drupal_container()->has('keyvalue'), 'The container has no keyvalue service.');
// Retrieving the location of a module.
$this->assertIdentical(drupal_get_filename('module', 'php'), 'core/modules/php/php.module', 'Retrieve module location.');
......
......@@ -30,11 +30,6 @@ public static function getInfo() {
* Tests DIC compilation.
*/
function testCompileDIC() {
// Because we'll be instantiating a new kernel during this test, the
// container stored in drupal_container() will be updated as a side effect.
// We need to be able to restore it to the correct one at the end of this
// test.
$original_container = drupal_container();
$classloader = drupal_classloader();
global $conf;
$conf['php_storage']['service_container']= array(
......@@ -63,9 +58,6 @@ function testCompileDIC() {
!$refClass->isSubclassOf('Symfony\Component\DependencyInjection\ContainerBuilder');
$this->assertTrue($is_compiled_container);
// Reset the container.
drupal_container(NULL, TRUE);
// Now use the read-only storage implementation, simulating a "production"
// environment.
$conf['php_storage']['service_container']['class'] = 'Drupal\Component\PhpStorage\FileReadOnlyStorage';
......@@ -89,9 +81,6 @@ function testCompileDIC() {
// modules.
$this->assertFalse($container->has('bundle_test_class'));
// Reset the container.
drupal_container(NULL, TRUE);
// Add another module so that we can test that the new module's bundle is
// registered to the new container.
$module_enabled['bundle_test'] = 'bundle_test';
......@@ -113,8 +102,5 @@ function testCompileDIC() {
$classloader = $container->get('class_loader');
$refClass = new ReflectionClass($classloader);
$this->assertTrue($refClass->hasMethod('getNamespaces'), 'Container has a classloader');
// Restore the original container.
drupal_container($original_container);
}
}
......@@ -134,6 +134,7 @@ protected function setUp() {
$this->variable_set('site_mail', 'simpletest@example.com');
drupal_set_time_limit($this->timeLimit);
$this->rebuildContainer();
$this->setup = TRUE;
}
......
......@@ -464,20 +464,6 @@ function update_check_requirements($skip_warnings = FALSE) {
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
drupal_maintenance_theme();
// @todo Remove after converting update.php to use DrupalKernel.
$container = drupal_container();
$container->register('database', 'Drupal\Core\Database\Connection')
->setFactoryClass('Drupal\Core\Database\Database')
->setFactoryMethod('getConnection')
->addArgument('default');
$container->register('lock', 'Drupal\Core\Lock\DatabaseLockBackend');
$container->register('router.dumper', '\Drupal\Core\Routing\MatcherDumper')
->addArgument(new Reference('database'));
$container->register('router.builder', 'Drupal\Core\Routing\RouteBuilder')
->addArgument(new Reference('router.dumper'))
->addArgument(new Reference('lock'))
->addArgument(new Reference('dispatcher'));
// Turn error reporting back on. From now on, only fatal errors (which are
// not passed through the error handler) will cause a message to be printed.
ini_set('display_errors', TRUE);
......
......@@ -30,6 +30,11 @@
// @todo Figure out how best to handle the Kernel constructor parameters.
$kernel = new DrupalKernel('prod', FALSE, drupal_classloader());
// @todo Remove this once everything in the bootstrap has been
// converted to services in the DIC.
$kernel->boot();
drupal_bootstrap(DRUPAL_BOOTSTRAP_CODE);
// Create a request object from the HTTPFoundation.
$request = Request::createFromGlobals();
$response = $kernel->handle($request)->prepare($request)->send();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment