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

This reverts commit 761ac67906.
8.0.x
catch 2012-11-29 20:41:30 +00:00
parent 761ac67906
commit a1638b87eb
14 changed files with 166 additions and 120 deletions

View File

@ -1,7 +1,6 @@
<?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;
@ -129,44 +128,39 @@ const WATCHDOG_DEBUG = 7;
const DRUPAL_BOOTSTRAP_CONFIGURATION = 0;
/**
* Second bootstrap phase, initalize a kernel.
* Second bootstrap phase: try to serve a cached page.
*/
const DRUPAL_BOOTSTRAP_KERNEL = 1;
const DRUPAL_BOOTSTRAP_PAGE_CACHE = 1;
/**
* Third bootstrap phase: try to serve a cached page.
* Third bootstrap phase: initialize database layer.
*/
const DRUPAL_BOOTSTRAP_PAGE_CACHE = 2;
const DRUPAL_BOOTSTRAP_DATABASE = 2;
/**
* Fourth bootstrap phase: initialize database layer.
* Fourth bootstrap phase: initialize the variable system.
*/
const DRUPAL_BOOTSTRAP_DATABASE = 3;
const DRUPAL_BOOTSTRAP_VARIABLES = 3;
/**
* Fifth bootstrap phase: initialize the variable system.
* Fifth bootstrap phase: initialize session handling.
*/
const DRUPAL_BOOTSTRAP_VARIABLES = 4;
const DRUPAL_BOOTSTRAP_SESSION = 4;
/**
* Sixth bootstrap phase: initialize session handling.
* Sixth bootstrap phase: set up the page header.
*/
const DRUPAL_BOOTSTRAP_SESSION = 5;
const DRUPAL_BOOTSTRAP_PAGE_HEADER = 5;
/**
* Seventh bootstrap phase: set up the page header.
* Seventh bootstrap phase: load code for subsystems and modules.
*/
const DRUPAL_BOOTSTRAP_PAGE_HEADER = 6;
/**
* Eighth bootstrap phase: load code for subsystems and modules.
*/
const DRUPAL_BOOTSTRAP_CODE = 7;
const DRUPAL_BOOTSTRAP_CODE = 6;
/**
* Final bootstrap phase: initialize language, path, theme, and modules.
*/
const DRUPAL_BOOTSTRAP_FULL = 8;
const DRUPAL_BOOTSTRAP_FULL = 7;
/**
* Role ID for anonymous users; should match what's in the "role" table.
@ -2111,7 +2105,6 @@ 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,
@ -2122,15 +2115,14 @@ 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 = -1;
static $final_phase;
// 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 during
// recursion. Additionally, ensure that $final_phase is never rolled back to an
// earlier bootstrap state.
if ($new_phase && $phase > $final_phase) {
// When not recursing, store the phase name so it's not forgotten while
// recursing.
if ($new_phase) {
$final_phase = $phase;
}
if (isset($phase)) {
@ -2150,10 +2142,6 @@ 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;
@ -2286,18 +2274,6 @@ 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.
*/
@ -2434,28 +2410,91 @@ function drupal_get_bootstrap_phase() {
/**
* Retrieves the Drupal Container to standardize object construction.
*
* 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'].
* 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.
*
* @see Drupal\Core\DrupalKernel
*
* @param Symfony\Component\DependencyInjection\Container $new_container
* (optional) A new container instance to replace the current.
* 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.
*
* @return Symfony\Component\DependencyInjection\Container|bool
* @return Symfony\Component\DependencyInjection\Container
* The instance of the Container used to set up and maintain object
* instances or FALSE if none exist yet.
* instances.
*/
function drupal_container(Container $new_container = NULL) {
function drupal_container(Container $new_container = NULL, $rebuild = FALSE) {
// 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;
static $container = NULL;
if ($rebuild) {
$container = NULL;
}
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;
}

View File

@ -5,12 +5,10 @@
* 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.
*
@ -560,7 +558,7 @@ function file_save_htaccess($directory, $private = TRUE) {
if ($private) {
// Private .htaccess file.
$htaccess_lines = MTimeProtectedFastFileStorage::HTACCESS;
$htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nDeny from all\nOptions None\nOptions +FollowSymLinks";
}
else {
// Public .htaccess file.

View File

@ -288,9 +288,6 @@ 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:
@ -312,15 +309,10 @@ 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 and the
// database has been set up successfully.
// This override is reverted as soon as the config directory has been set up
// successfully.
// @see drupal_install_config_directories()
// @see install_settings_form_submit()
if ($install_state['settings_verified']) {
$kernel = new DrupalKernel('install', FALSE, drupal_classloader(), FALSE);
$kernel->boot();
}
else {
if (!$install_state['config_verified']) {
// @todo Move into a proper Drupal\Core\DependencyInjection\InstallContainerBuilder.
$container = new ContainerBuilder();
@ -370,6 +362,10 @@ 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.
@ -1108,6 +1104,11 @@ 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
@ -1499,6 +1500,10 @@ 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);
}

View File

@ -6,7 +6,6 @@
*/
use Drupal\Core\Database\Database;
use Drupal\Core\DrupalKernel;
use Drupal\locale\Gettext;
/**
@ -422,9 +421,6 @@ 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';

View File

@ -83,10 +83,6 @@ class FileStorage implements PhpStorageInterface {
* 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'));
}

View File

@ -40,8 +40,6 @@ use DirectoryIterator;
*/
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.
*
@ -146,10 +144,7 @@ class MTimeProtectedFastFileStorage extends FileStorage {
mkdir($this->directory, 0700, TRUE);
}
chmod($this->directory, 0700);
$htaccess_path = $this->directory . '/.htaccess';
if (!file_exists($htaccess_path) && file_put_contents($htaccess_path, self::HTACCESS)) {
@chmod($htaccess_path, 0444);
}
file_save_htaccess($this->directory);
}
/**

View File

@ -158,6 +158,11 @@ class DrupalKernel extends Kernel implements DrupalKernelInterface {
}
$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');
}

View File

@ -8,7 +8,6 @@
namespace Drupal\simpletest;
use Drupal\Core\DrupalKernel;
use Symfony\Component\DependencyInjection\Reference;
use Drupal\Core\Database\Database;
use Symfony\Component\DependencyInjection\ContainerInterface;
@ -130,21 +129,6 @@ abstract class DrupalUnitTestBase extends UnitTestBase {
$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'));
}
}
/**

View File

@ -8,7 +8,6 @@
namespace Drupal\simpletest;
use Drupal\Core\Database\Database;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Database\ConnectionNotDefinedException;
use Drupal\Core\DrupalKernel;
use ReflectionMethod;
@ -820,9 +819,7 @@ abstract class TestBase {
$this->originalContainer = clone drupal_container();
$this->originalLanguage = $language_interface;
$this->originalConfigDirectories = $GLOBALS['config_directories'];
if (isset($GLOBALS['theme_key'])) {
$this->originalThemeKey = $GLOBALS['theme_key'];
}
$this->originalThemeKey = isset($GLOBALS['theme_key']) ? $GLOBALS['theme_key'] : NULL;
$this->originalTheme = isset($GLOBALS['theme']) ? $GLOBALS['theme'] : NULL;
// Save further contextual information.
@ -876,8 +873,7 @@ abstract class TestBase {
}
// Reset and create a new service container.
$this->container = new ContainerBuilder();
drupal_container($this->container);
$this->container = drupal_container(NULL, TRUE);
// Unset globals.
unset($GLOBALS['theme_key']);
@ -910,6 +906,9 @@ abstract class TestBase {
* 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()
@ -967,13 +966,11 @@ abstract class TestBase {
// 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);
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'));
}
$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.
@ -988,9 +985,7 @@ abstract class TestBase {
$databases['default']['default'] = $connection_info['default'];
// Restore original globals.
if (isset($this->originalThemeKey)) {
$GLOBALS['theme_key'] = $this->originalThemeKey;
}
$GLOBALS['theme_key'] = $this->originalThemeKey;
$GLOBALS['theme'] = $this->originalTheme;
// Reset all static variables.

View File

@ -22,13 +22,24 @@ class GetFilenameUnitTest extends UnitTestBase {
);
}
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.');

View File

@ -30,6 +30,11 @@ class DrupalKernelTest extends UnitTestBase {
* 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(
@ -58,6 +63,9 @@ class DrupalKernelTest extends UnitTestBase {
!$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';
@ -81,6 +89,9 @@ class DrupalKernelTest extends UnitTestBase {
// 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';
@ -102,5 +113,8 @@ class DrupalKernelTest extends UnitTestBase {
$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);
}
}

View File

@ -134,7 +134,6 @@ abstract class UpgradePathTestBase extends WebTestBase {
$this->variable_set('site_mail', 'simpletest@example.com');
drupal_set_time_limit($this->timeLimit);
$this->rebuildContainer();
$this->setup = TRUE;
}

View File

@ -464,6 +464,20 @@ update_fix_d8_requirements();
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);

View File

@ -30,11 +30,6 @@ drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
// @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();