DrupalKernel.php 19.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Definition of Drupal\Core\DrupalKernel.
 */

namespace Drupal\Core;

10 11
use Drupal\Component\PhpStorage\PhpStorageFactory;
use Drupal\Core\Config\BootstrapConfigStorageFactory;
12
use Drupal\Core\CoreBundle;
13
use Drupal\Core\DependencyInjection\ContainerBuilder;
14
use Drupal\Core\DependencyInjection\YamlFileLoader;
15
use Symfony\Component\ClassLoader\ClassLoader;
16 17
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
18
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
19
use Symfony\Component\HttpKernel\Kernel;
20 21 22

/**
 * The DrupalKernel class is the core of Drupal itself.
23 24 25 26 27 28 29
 *
 * This class is responsible for building the Dependency Injection Container and
 * also deals with the registration of bundles. It allows registered bundles to
 * add their services to the container. Core provides the CoreBundle, which adds
 * the services required for all core subsystems. Each module can then add its
 * own bundle, i.e. a subclass of Symfony\Component\HttpKernel\Bundle, to
 * register services to the container.
30
 */
31
class DrupalKernel extends Kernel implements DrupalKernelInterface {
32

33 34 35 36
  /**
   * Holds the list of enabled modules.
   *
   * @var array
37 38
   *   An associative array whose keys are module names and whose values are
   *   ignored.
39 40 41 42
   */
  protected $moduleList;

  /**
43
   * Holds an updated list of enabled modules.
44
   *
45 46 47 48 49 50 51 52 53 54 55 56 57
   * @var array
   *   An associative array whose keys are module names and whose values are
   *   ignored.
   */
  protected $newModuleList;

  /**
   * An array of module data objects.
   *
   * The data objects have the same data structure as returned by
   * file_scan_directory() but only the uri property is used.
   *
   * @var array
58
   */
59
  protected $moduleData = array();
60 61 62 63 64 65 66 67

  /**
   * PHP code storage object to use for the compiled container.
   *
   * @var \Drupal\Component\PhpStorage\PhpStorageInterface
   */
  protected $storage;

68 69 70
  /**
   * The classloader object.
   *
71
   * @var \Symfony\Component\ClassLoader\ClassLoader
72 73 74
   */
  protected $classLoader;

75 76 77 78 79 80 81
  /**
   * Config storage object used for reading enabled modules configuration.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $configStorage;

82 83 84 85 86 87 88
  /**
   * The list of the classnames of the bundles in this kernel.
   *
   * @var array
   */
  protected $bundleClasses;

89 90 91 92 93 94 95 96 97 98 99 100 101 102
  /**
   * Whether the container can be dumped.
   *
   * @var bool
   */
  protected $allowDumping;

  /**
   * Whether the container needs to be dumped once booting is complete.
   *
   * @var bool
   */
  protected $containerNeedsDumping;

103 104 105 106 107 108 109
  /**
   * Holds the list of YAML files containing service definitions.
   *
   * @var array
   */
  protected $serviceYamls;

110 111 112 113 114 115 116 117 118 119 120
  /**
   * Constructs a DrupalKernel object.
   *
   * @param string $environment
   *   String indicating the environment, e.g. 'prod' or 'dev'. Used by
   *   Symfony\Component\HttpKernel\Kernel::__construct(). Drupal does not use
   *   this value currently. Pass 'prod'.
   * @param bool $debug
   *   Boolean indicating whether we are in debug mode. Used by
   *   Symfony\Component\HttpKernel\Kernel::__construct(). Drupal does not use
   *   this value currently. Pass TRUE.
121
   * @param \Symfony\Component\ClassLoader\ClassLoader $class_loader
122 123 124 125
   *   (optional) The classloader is only used if $storage is not given or
   *   the load from storage fails and a container rebuild is required. In
   *   this case, the loaded modules will be registered with this loader in
   *   order to be able to find the module bundles.
126 127 128
   * @param bool $allow_dumping
   *   (optional) FALSE to stop the container from being written to or read
   *   from disk. Defaults to TRUE.
129
   */
130
  public function __construct($environment, $debug, ClassLoader $class_loader, $allow_dumping = TRUE) {
131
    parent::__construct($environment, $debug);
132
    $this->classLoader = $class_loader;
133
    $this->allowDumping = $allow_dumping;
134 135
  }

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  /**
   * {@inheritdoc}
   */
  public function serialize() {
    return serialize(array($this->environment, $this->debug, $this->classLoader, $this->allowDumping));
  }

  /**
   * {@inheritdoc}
   */
  public function unserialize($data) {
    list($environment, $debug, $class_loader, $allow_dumping) = unserialize($data);
    $this->__construct($environment, $debug, $class_loader, $allow_dumping);
  }

151 152 153 154 155 156 157 158 159 160
  /**
   * Overrides Kernel::init().
   */
  public function init() {
    // Intentionally empty. The sole purpose is to not execute Kernel::init(),
    // since that overrides/breaks Drupal's current error handling.
    // @todo Investigate whether it is possible to migrate Drupal's error
    //   handling to the one of Kernel without losing functionality.
  }

161 162 163 164 165 166 167 168 169
  /**
   * Overrides Kernel::boot().
   */
  public function boot() {
    if ($this->booted) {
      return;
    }
    $this->initializeContainer();
    $this->booted = TRUE;
170 171 172
    if ($this->containerNeedsDumping && !$this->dumpDrupalContainer($this->container, $this->getContainerBaseClass())) {
      watchdog('DrupalKernel', 'Container cannot be written to disk');
    }
173 174
  }

175 176
  /**
   * Returns an array of available bundles.
177 178 179
   *
   * @return array
   *   The available bundles.
180
   */
181
  public function registerBundles() {
182
    $this->configStorage = BootstrapConfigStorageFactory::get();
183
    $bundles = array(
184
      new CoreBundle(),
185
    );
186 187 188
    $this->serviceYamls = array(
      'core/core.services.yml'
    );
189
    $this->bundleClasses = array('Drupal\Core\CoreBundle');
190 191 192

    // Ensure we know what modules are enabled and that their namespaces are
    // registered.
193
    if (!isset($this->moduleList)) {
194
      $module_list = $this->configStorage->read('system.module');
195 196
      $this->moduleList = isset($module_list['enabled']) ? $module_list['enabled'] : array();
    }
197 198
    $module_filenames = $this->getModuleFileNames();
    $this->registerNamespaces($this->getModuleNamespaces($module_filenames));
199

200
    // Load each module's bundle class.
201
    foreach ($this->moduleList as $module => $weight) {
katbailey's avatar
katbailey committed
202
      $camelized = ContainerBuilder::camelize($module);
203
      $class = "Drupal\\{$module}\\{$camelized}Bundle";
204 205
      if (class_exists($class)) {
        $bundles[] = new $class();
206
        $this->bundleClasses[] = $class;
207
      }
208 209 210 211
      $filename = dirname($module_filenames[$module]) . "/$module.services.yml";
      if (file_exists($filename)) {
        $this->serviceYamls[] = $filename;
      }
212
    }
213

214 215 216 217 218 219 220
    // Add site specific or test bundles.
    if (!empty($GLOBALS['conf']['container_bundles'])) {
      foreach ($GLOBALS['conf']['container_bundles'] as $class) {
        $bundles[] = new $class();
        $this->bundleClasses[] = $class;
      }
    }
221 222 223 224
    // Add site specific or test YAMLs.
    if (!empty($GLOBALS['conf']['container_yamls'])) {
      $this->serviceYamls = array_merge($this->serviceYamls, $GLOBALS['conf']['container_yamls']);
    }
225 226
    return $bundles;
  }
227

228 229 230 231 232 233 234 235 236 237 238 239 240
  /**
   * Returns module data on the filesystem.
   *
   * @param $module
   *   The name of the module.
   *
   * @return \stdClass|bool
   *   Returns a stdClass object if the module data is found containing at
   *   least an uri property with the module path, for example
   *   core/modules/user/user.module.
   */
  protected function moduleData($module) {
    if (!$this->moduleData) {
241
      // First, find profiles.
242 243 244 245 246
      $profiles_scanner = new SystemListing();
      $all_profiles = $profiles_scanner->scan('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.profile$/', 'profiles');
      $profiles = array_keys(array_intersect_key($this->moduleList, $all_profiles));
      // If a module is within a profile directory but specifies another
      // profile for testing, it needs to be found in the parent profile.
247
      if (($parent_profile_config = $this->configStorage->read('simpletest.settings')) && isset($parent_profile_config['parent_profile']) && $parent_profile_config['parent_profile'] != $profiles[0]) {
248 249 250 251 252 253 254 255 256 257 258
        // In case both profile directories contain the same extension, the
        // actual profile always has precedence.
        array_unshift($profiles, $parent_profile_config['parent_profile']);
      }
      // Now find modules.
      $modules_scanner = new SystemListing($profiles);
      $this->moduleData = $all_profiles + $modules_scanner->scan('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.module$/', 'modules');
    }
    return isset($this->moduleData[$module]) ? $this->moduleData[$module] : FALSE;
  }

259 260
  /**
   * Implements Drupal\Core\DrupalKernelInterface::updateModules().
261 262 263
   *
   * @todo Remove obsolete $module_list parameter. Only $module_filenames is
   *   needed.
264
   */
265
  public function updateModules(array $module_list, array $module_filenames = array()) {
266
    $this->newModuleList = $module_list;
267 268
    foreach ($module_filenames as $module => $filename) {
      $this->moduleData[$module] = (object) array('uri' => $filename);
269
    }
270 271 272 273 274 275 276 277
    // If we haven't yet booted, we don't need to do anything: the new module
    // list will take effect when boot() is called. If we have already booted,
    // then reboot in order to refresh the bundle list and container.
    if ($this->booted) {
      $this->booted = FALSE;
      $this->boot();
    }
  }
278

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
  /**
   * Returns the classname based on environment, debug and testing prefix.
   *
   * @return string
   *   The class name.
   */
  protected function getClassName() {
    $parts = array('service_container', $this->environment, $this->debug);
    // Make sure to use a testing-specific container even in the parent site.
    if (!empty($GLOBALS['drupal_test_info']['test_run_id'])) {
      $parts[] = $GLOBALS['drupal_test_info']['test_run_id'];
    }
    elseif ($prefix = drupal_valid_test_ua()) {
      $parts[] = $prefix;
    }
    return implode('_', $parts);
  }

297 298 299
  /**
   * Initializes the service container.
   */
300
  protected function initializeContainer() {
301
    $persist = $this->getServicesToPersist();
302 303 304 305 306
    // If we are rebuilding the kernel and we are in a request scope, store
    // request info so we can add them back after the rebuild.
    if (isset($this->container) && $this->container->hasScope('request')) {
      $request = $this->container->get('request');
    }
307
    $this->container = NULL;
308 309 310
    $class = $this->getClassName();
    $cache_file = $class . '.php';

311
    if ($this->allowDumping) {
312 313
      // First, try to load.
      if (!class_exists($class, FALSE)) {
314
        $this->storage()->load($cache_file);
315 316 317 318 319
      }
      // If the load succeeded or the class already existed, use it.
      if (class_exists($class, FALSE)) {
        $fully_qualified_class_name = '\\' . $class;
        $this->container = new $fully_qualified_class_name;
320
        $this->persistServices($persist);
321 322
      }
    }
323 324 325 326 327 328 329 330
    // First check whether the list of modules changed in this request.
    if (isset($this->newModuleList)) {
      if (isset($this->container) && isset($this->moduleList) && array_keys($this->moduleList) !== array_keys($this->newModuleList)) {
        unset($this->container);
      }
      $this->moduleList = $this->newModuleList;
      unset($this->newModuleList);
    }
331 332
    // Second, check if some other request -- for example on another web
    // frontend or during the installer -- changed the list of enabled modules.
333
    if (isset($this->container)) {
334 335
      // All namespaces must be registered before we attempt to use any service
      // from the container.
336
      $container_modules = $this->container->getParameter('container.modules');
337
      $namespaces_before = $this->classLoader->getPrefixes();
338
      $this->registerNamespaces($this->getModuleNamespaces($container_modules));
339 340 341 342

      // If 'container.modules' is wrong, the container must be rebuilt.
      if (!isset($this->moduleList)) {
        $this->moduleList = $this->container->get('config.factory')->get('system.module')->load()->get('enabled');
343
      }
344
      if (array_keys($this->moduleList) !== array_keys($container_modules)) {
345
        $persist = $this->getServicesToPersist();
346
        unset($this->container);
347 348 349 350
        // Revert the class loader to its prior state. However,
        // registerNamespaces() performs a merge rather than replace, so to
        // effectively remove erroneous registrations, we must replace them with
        // empty arrays.
351
        $namespaces_after = $this->classLoader->getPrefixes();
352
        $namespaces_before += array_fill_keys(array_diff(array_keys($namespaces_after), array_keys($namespaces_before)), array());
353
        $this->registerNamespaces($namespaces_before);
354 355 356
      }
    }

357 358
    if (!isset($this->container)) {
      $this->container = $this->buildContainer();
359
      $this->persistServices($persist);
360 361 362 363 364 365 366 367

      // The namespaces are marked as persistent, so objects like the annotated
      // class discovery still has the right object. We may have updated the
      // list of modules, so set it.
      if ($this->container->initialized('container.namespaces')) {
        $this->container->get('container.namespaces')->exchangeArray($this->container->getParameter('container.namespaces'));
      }

368 369
      if ($this->allowDumping) {
        $this->containerNeedsDumping = TRUE;
370 371 372
      }
    }

373
    $this->container->set('kernel', $this);
374 375
    // Set the class loader which was registered as a synthetic service.
    $this->container->set('class_loader', $this->classLoader);
376 377 378 379 380
    // If we have a request set it back to the new container.
    if (isset($request)) {
      $this->container->enterScope('request');
      $this->container->set('request', $request);
    }
381
    \Drupal::setContainer($this->container);
382
  }
383

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  /**
   * Returns service instances to persist from an old container to a new one.
   */
  protected function getServicesToPersist() {
    $persist = array();
    if (isset($this->container)) {
      foreach ($this->container->getParameter('persistIds') as $id) {
        // It's pointless to persist services not yet initialized.
        if ($this->container->initialized($id)) {
          $persist[$id] = $this->container->get($id);
        }
      }
    }
    return $persist;
  }

  /**
   * Moves persistent service instances into a new container.
   */
  protected function persistServices(array $persist) {
    foreach ($persist as $id => $object) {
      // Do not override services already set() on the new container, for
      // example 'service_container'.
      if (!$this->container->initialized($id)) {
        $this->container->set($id, $object);
      }
    }
  }

413 414 415 416 417
  /**
   * Builds the service container.
   *
   * @return ContainerBuilder The compiled service container
   */
418
  protected function buildContainer() {
419
    $this->initializeBundles();
420
    $container = $this->getContainerBuilder();
421
    $container->setParameter('container.bundles', $this->bundleClasses);
422
    $container->setParameter('container.modules', $this->getModuleFileNames());
423 424 425

    // Get a list of namespaces and put it onto the container.
    $namespaces = $this->getModuleNamespaces($this->getModuleFileNames());
426 427 428 429 430 431
    // Add all components in \Drupal\Core and \Drupal\Component that have a
    // Plugin directory.
    foreach (array('Core', 'Component') as $parent_directory) {
      $path = DRUPAL_ROOT . '/core/lib/Drupal/' . $parent_directory;
      foreach (new \DirectoryIterator($path) as $component) {
        if (!$component->isDot() && is_dir($component->getPathname() . '/Plugin')) {
432
          $namespaces['Drupal\\' . $parent_directory  .'\\' . $component->getFilename()] = DRUPAL_ROOT . '/core/lib';
433 434 435
        }
      }
    }
436 437
    $container->setParameter('container.namespaces', $namespaces);

438
    // Register synthetic services.
439
    $container->register('class_loader', 'Symfony\Component\ClassLoader\ClassLoader')->setSynthetic(TRUE);
440 441
    $container->register('kernel', 'Symfony\Component\HttpKernel\KernelInterface')->setSynthetic(TRUE);
    $container->register('service_container', 'Symfony\Component\DependencyInjection\ContainerInterface')->setSynthetic(TRUE);
442 443 444 445
    $yaml_loader = new YamlFileLoader($container);
    foreach ($this->serviceYamls as $filename) {
      $yaml_loader->load($filename);
    }
446 447
    foreach ($this->bundles as $bundle) {
      $bundle->build($container);
448
    }
449 450 451 452 453 454 455 456 457 458 459 460 461

    // Identify all services whose instances should be persisted when rebuilding
    // the container during the lifetime of the kernel (e.g., during a kernel
    // reboot). Include synthetic services, because by definition, they cannot
    // be automatically reinstantiated. Also include services tagged to persist.
    $persist_ids = array();
    foreach ($container->getDefinitions() as $id => $definition) {
      if ($definition->isSynthetic() || $definition->getTag('persist')) {
        $persist_ids[] = $id;
      }
    }
    $container->setParameter('persistIds', $persist_ids);

462
    $container->compile();
463 464
    return $container;
  }
465

466 467 468 469 470
  /**
   * Gets a new ContainerBuilder instance used to build the service container.
   *
   * @return ContainerBuilder
   */
471
  protected function getContainerBuilder() {
472 473 474
    return new ContainerBuilder(new ParameterBag($this->getKernelParameters()));
  }

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  /**
   * Dumps the service container to PHP code in the config directory.
   *
   * This method is based on the dumpContainer method in the parent class, but
   * that method is reliant on the Config component which we do not use here.
   *
   * @param ContainerBuilder $container
   *   The service container.
   * @param string $baseClass
   *   The name of the container's base class
   *
   * @return bool
   *   TRUE if the container was successfully dumped to disk.
   */
  protected function dumpDrupalContainer(ContainerBuilder $container, $baseClass) {
490
    if (!$this->storage()->writeable()) {
491 492 493 494
      return FALSE;
    }
    // Cache the container.
    $dumper = new PhpDumper($container);
495 496
    $class = $this->getClassName();
    $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass));
497
    return $this->storage()->save($class . '.php', $content);
498 499
  }

katbailey's avatar
katbailey committed
500
  /**
Crell's avatar
Crell committed
501 502
   * Overrides and eliminates this method from the parent class. Do not use.
   *
katbailey's avatar
katbailey committed
503 504 505 506 507 508 509
   * This method is part of the KernelInterface interface, but takes an object
   * implementing LoaderInterface as its only parameter. This is part of the
   * Config compoment from Symfony, which is not provided by Drupal core.
   *
   * Modules wishing to provide an extension to this class which uses this
   * method are responsible for ensuring the Config component exists.
   */
510
  public function registerContainerConfiguration(LoaderInterface $loader) {
511
  }
512

513 514 515 516 517 518 519 520 521 522 523 524
  /**
   * Gets the PHP code storage object to use for the compiled container.
   *
   * @return \Drupal\Component\PhpStorage\PhpStorageInterface
   */
  protected function storage() {
    if (!isset($this->storage)) {
      $this->storage = PhpStorageFactory::get('service_container');
    }
    return $this->storage;
  }

525 526 527 528 529 530 531 532 533 534 535 536 537 538
  /**
   * Returns the file name for each enabled module.
   */
  protected function getModuleFileNames() {
    $filenames = array();
    foreach ($this->moduleList as $module => $weight) {
      if ($data = $this->moduleData($module)) {
        $filenames[$module] = $data->uri;
      }
    }
    return $filenames;
  }

  /**
539
   * Gets the namespaces of each enabled module.
540
   */
541 542
  protected function getModuleNamespaces($moduleFileNames) {
    $namespaces = array();
543
    foreach ($moduleFileNames as $module => $filename) {
544 545 546 547 548 549 550 551 552
      $namespaces["Drupal\\$module"] = DRUPAL_ROOT . '/' . dirname($filename) . '/lib';
    }
    return $namespaces;
  }

  /**
   * Registers a list of namespaces.
   */
  protected function registerNamespaces(array $namespaces = array()) {
553
    $this->classLoader->addPrefixes($namespaces);
554
  }
555
}