DrupalKernel.php 21.6 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\CoreServiceProvider;
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 20 21 22
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
23 24 25

/**
 * The DrupalKernel class is the core of Drupal itself.
26 27
 *
 * This class is responsible for building the Dependency Injection Container and
28 29 30 31 32 33 34 35
 * also deals with the registration of service providers. It allows registered
 * service providers to add their services to the container. Core provides the
 * CoreServiceProvider, which, in addition to registering any core services that
 * cannot be registered in the core.services.yaml file, adds any compiler passes
 * needed by core, e.g. for processing tagged services. Each module can add its
 * own service provider, i.e. a class implementing
 * Drupal\Core\DependencyInjection\ServiceProvider, to register services to the
 * container, or modify existing services.
36
 */
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
class DrupalKernel implements DrupalKernelInterface, TerminableInterface {

  const CONTAINER_BASE_CLASS = 'Container';

  /**
   * Holds the container instance.
   *
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected $container;

  /**
   * The environment, e.g. 'testing', 'install'.
   *
   * @var string
   */
  protected $environment;

  /**
   * Whether the kernel has been booted.
   *
   * @var bool
   */
  protected $booted;
61

62 63 64 65
  /**
   * Holds the list of enabled modules.
   *
   * @var array
66 67
   *   An associative array whose keys are module names and whose values are
   *   ignored.
68 69 70 71
   */
  protected $moduleList;

  /**
72
   * Holds an updated list of enabled modules.
73
   *
74 75 76 77 78 79 80 81 82 83 84 85 86
   * @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
87
   */
88
  protected $moduleData = array();
89 90 91 92 93 94 95 96

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

97 98 99
  /**
   * The classloader object.
   *
100
   * @var \Symfony\Component\ClassLoader\ClassLoader
101 102 103
   */
  protected $classLoader;

104 105 106 107 108 109 110
  /**
   * Config storage object used for reading enabled modules configuration.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $configStorage;

111
  /**
112
   * The list of the classnames of the service providers in this kernel.
113 114 115
   *
   * @var array
   */
116
  protected $serviceProviderClasses;
117

118 119 120 121 122 123 124 125 126 127 128 129 130 131
  /**
   * 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;

132 133 134 135 136 137 138
  /**
   * Holds the list of YAML files containing service definitions.
   *
   * @var array
   */
  protected $serviceYamls;

139 140 141 142 143 144 145
  /**
   * The array of registered service providers.
   *
   * @var array
   */
  protected $serviceProviders;

146 147 148 149 150 151 152
  /**
   * 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'.
153
   * @param \Symfony\Component\ClassLoader\ClassLoader $class_loader
154 155 156
   *   (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
157
   *   order to be able to find the module serviceProviders.
158 159 160
   * @param bool $allow_dumping
   *   (optional) FALSE to stop the container from being written to or read
   *   from disk. Defaults to TRUE.
161
   */
162 163 164
  public function __construct($environment, ClassLoader $class_loader, $allow_dumping = TRUE) {
    $this->environment = $environment;
    $this->booted = false;
165
    $this->classLoader = $class_loader;
166
    $this->allowDumping = $allow_dumping;
167 168
  }

169 170 171 172
  /**
   * {@inheritdoc}
   */
  public function serialize() {
173
    return serialize(array($this->environment, $this->classLoader, $this->allowDumping));
174 175 176 177 178 179
  }

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

184
  /**
185
   * {@inheritdoc}
186 187 188 189 190 191 192
   */
  public function boot() {
    if ($this->booted) {
      return;
    }
    $this->initializeContainer();
    $this->booted = TRUE;
193
    if ($this->containerNeedsDumping && !$this->dumpDrupalContainer($this->container, static::CONTAINER_BASE_CLASS)) {
194 195
      watchdog('DrupalKernel', 'Container cannot be written to disk');
    }
196 197
  }

198
  /**
199
   * {@inheritdoc}
200
   */
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
  public function shutdown() {
    if (FALSE === $this->booted) {
      return;
    }
    $this->booted = FALSE;
    $this->container = null;
  }

  /**
   * {@inheritdoc}
   */
  public function getContainer() {
    return $this->container;
  }

  /**
   * {@inheritdoc}
   */
  public function discoverServiceProviders() {
220
    $this->configStorage = BootstrapConfigStorageFactory::get();
221 222
    $serviceProviders = array(
      'CoreServiceProvider' => new CoreServiceProvider(),
223
    );
224 225 226
    $this->serviceYamls = array(
      'core/core.services.yml'
    );
227
    $this->serviceProviderClasses = array('Drupal\Core\CoreServiceProvider');
228 229 230

    // Ensure we know what modules are enabled and that their namespaces are
    // registered.
231
    if (!isset($this->moduleList)) {
232
      $module_list = $this->configStorage->read('system.module');
233 234
      $this->moduleList = isset($module_list['enabled']) ? $module_list['enabled'] : array();
    }
235 236
    $module_filenames = $this->getModuleFileNames();
    $this->registerNamespaces($this->getModuleNamespaces($module_filenames));
237

238
    // Load each module's serviceProvider class.
239
    foreach ($this->moduleList as $module => $weight) {
katbailey's avatar
katbailey committed
240
      $camelized = ContainerBuilder::camelize($module);
241 242
      $name = "{$camelized}ServiceProvider";
      $class = "Drupal\\{$module}\\{$name}";
243
      if (class_exists($class)) {
244 245
        $serviceProviders[$name] = new $class();
        $this->serviceProviderClasses[] = $class;
246
      }
247 248 249 250
      $filename = dirname($module_filenames[$module]) . "/$module.services.yml";
      if (file_exists($filename)) {
        $this->serviceYamls[] = $filename;
      }
251
    }
252

253 254 255 256 257
    // Add site specific or test service providers.
    if (!empty($GLOBALS['conf']['container_service_providers'])) {
      foreach ($GLOBALS['conf']['container_service_providers'] as $name => $class) {
        $serviceProviders[$name] = new $class();
        $this->serviceProviderClasses[] = $class;
258 259
      }
    }
260 261 262 263
    // Add site specific or test YAMLs.
    if (!empty($GLOBALS['conf']['container_yamls'])) {
      $this->serviceYamls = array_merge($this->serviceYamls, $GLOBALS['conf']['container_yamls']);
    }
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    return $serviceProviders;
  }


  /**
   * {@inheritdoc}
   */
  public function getServiceProviders() {
    return $this->serviceProviders;
  }

  /**
   * {@inheritdoc}
   */
  public function terminate(Request $request, Response $response) {
    if (FALSE === $this->booted) {
      return;
    }

    if ($this->getHttpKernel() instanceof TerminableInterface) {
      $this->getHttpKernel()->terminate($request, $response);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) {
    if (FALSE === $this->booted) {
      $this->boot();
    }

    return $this->getHttpKernel()->handle($request, $type, $catch);
297
  }
298

299 300 301 302 303 304 305 306 307 308 309 310 311
  /**
   * 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) {
312
      // First, find profiles.
313 314 315 316 317
      $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.
318
      if (($parent_profile_config = $this->configStorage->read('simpletest.settings')) && isset($parent_profile_config['parent_profile']) && $parent_profile_config['parent_profile'] != $profiles[0]) {
319 320 321 322 323 324 325 326 327 328 329
        // 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;
  }

330 331
  /**
   * Implements Drupal\Core\DrupalKernelInterface::updateModules().
332 333 334
   *
   * @todo Remove obsolete $module_list parameter. Only $module_filenames is
   *   needed.
335
   */
336
  public function updateModules(array $module_list, array $module_filenames = array()) {
337
    $this->newModuleList = $module_list;
338 339
    foreach ($module_filenames as $module => $filename) {
      $this->moduleData[$module] = (object) array('uri' => $filename);
340
    }
341 342
    // 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,
343
    // then reboot in order to refresh the serviceProvider list and container.
344 345 346 347 348
    if ($this->booted) {
      $this->booted = FALSE;
      $this->boot();
    }
  }
349

350
  /**
351
   * Returns the classname based on environment and testing prefix.
352 353 354 355 356
   *
   * @return string
   *   The class name.
   */
  protected function getClassName() {
357
    $parts = array('service_container', $this->environment);
358 359 360 361 362 363 364 365 366 367
    // 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);
  }

368 369 370 371 372 373 374 375 376 377 378 379

  /**
   * Returns the kernel parameters.
   *
   * @return array An array of kernel parameters
   */
  protected function getKernelParameters() {
    return array(
      'kernel.environment' => $this->environment,
    );
  }

380 381 382
  /**
   * Initializes the service container.
   */
383
  protected function initializeContainer() {
384
    $persist = $this->getServicesToPersist();
385 386 387 388 389
    // 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');
    }
390
    $this->container = NULL;
391 392 393
    $class = $this->getClassName();
    $cache_file = $class . '.php';

394
    if ($this->allowDumping) {
395 396
      // First, try to load.
      if (!class_exists($class, FALSE)) {
397
        $this->storage()->load($cache_file);
398 399 400 401 402
      }
      // 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;
403
        $this->persistServices($persist);
404 405
      }
    }
406 407 408 409 410 411 412 413
    // 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);
    }
414 415
    // Second, check if some other request -- for example on another web
    // frontend or during the installer -- changed the list of enabled modules.
416
    if (isset($this->container)) {
417 418
      // All namespaces must be registered before we attempt to use any service
      // from the container.
419
      $container_modules = $this->container->getParameter('container.modules');
420
      $namespaces_before = $this->classLoader->getPrefixes();
421
      $this->registerNamespaces($this->getModuleNamespaces($container_modules));
422 423 424 425

      // 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');
426
      }
427
      if (array_keys($this->moduleList) !== array_keys($container_modules)) {
428
        $persist = $this->getServicesToPersist();
429
        unset($this->container);
430 431 432 433
        // 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.
434
        $namespaces_after = $this->classLoader->getPrefixes();
435
        $namespaces_before += array_fill_keys(array_diff(array_keys($namespaces_after), array_keys($namespaces_before)), array());
436
        $this->registerNamespaces($namespaces_before);
437 438 439
      }
    }

440 441
    if (!isset($this->container)) {
      $this->container = $this->buildContainer();
442
      $this->persistServices($persist);
443 444 445 446 447 448 449 450

      // 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'));
      }

451 452
      if ($this->allowDumping) {
        $this->containerNeedsDumping = TRUE;
453 454 455
      }
    }

456
    $this->container->set('kernel', $this);
457

458 459
    // Set the class loader which was registered as a synthetic service.
    $this->container->set('class_loader', $this->classLoader);
460 461 462 463 464
    // If we have a request set it back to the new container.
    if (isset($request)) {
      $this->container->enterScope('request');
      $this->container->set('request', $request);
    }
465
    \Drupal::setContainer($this->container);
466
  }
467

468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
  /**
   * 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);
      }
    }
  }

497 498 499 500 501
  /**
   * Builds the service container.
   *
   * @return ContainerBuilder The compiled service container
   */
502
  protected function buildContainer() {
503
    $this->initializeServiceProviders();
504
    $container = $this->getContainerBuilder();
505 506
    $container->set('kernel', $this);
    $container->setParameter('container.service_providers', $this->serviceProviderClasses);
507
    $container->setParameter('container.modules', $this->getModuleFileNames());
508 509 510

    // Get a list of namespaces and put it onto the container.
    $namespaces = $this->getModuleNamespaces($this->getModuleFileNames());
511 512 513 514 515 516
    // 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')) {
517
          $namespaces['Drupal\\' . $parent_directory  .'\\' . $component->getFilename()] = DRUPAL_ROOT . '/core/lib';
518 519 520
        }
      }
    }
521 522
    $container->setParameter('container.namespaces', $namespaces);

523
    // Register synthetic services.
524
    $container->register('class_loader', 'Symfony\Component\ClassLoader\ClassLoader')->setSynthetic(TRUE);
525 526
    $container->register('kernel', 'Symfony\Component\HttpKernel\KernelInterface')->setSynthetic(TRUE);
    $container->register('service_container', 'Symfony\Component\DependencyInjection\ContainerInterface')->setSynthetic(TRUE);
527 528 529 530
    $yaml_loader = new YamlFileLoader($container);
    foreach ($this->serviceYamls as $filename) {
      $yaml_loader->load($filename);
    }
531 532
    foreach ($this->serviceProviders as $provider) {
      $provider->register($container);
533
    }
534 535 536 537 538 539 540 541 542 543 544 545 546

    // 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);

547
    $container->compile();
548 549
    return $container;
  }
550

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
  /**
   * Registers all service providers to the kernel.
   *
   * @throws \LogicException
   */
  protected function initializeServiceProviders() {
    $this->serviceProviders = array();

    foreach ($this->discoverServiceProviders() as $name => $provider) {
      if (isset($this->serviceProviders[$name])) {
        throw new \LogicException(sprintf('Trying to register two service providers with the same name "%s"', $name));
      }
      $this->serviceProviders[$name] = $provider;
    }
  }

567 568 569 570 571
  /**
   * Gets a new ContainerBuilder instance used to build the service container.
   *
   * @return ContainerBuilder
   */
572
  protected function getContainerBuilder() {
573 574 575
    return new ContainerBuilder(new ParameterBag($this->getKernelParameters()));
  }

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
  /**
   * 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) {
591
    if (!$this->storage()->writeable()) {
592 593 594 595
      return FALSE;
    }
    // Cache the container.
    $dumper = new PhpDumper($container);
596 597
    $class = $this->getClassName();
    $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass));
598
    return $this->storage()->save($class . '.php', $content);
599 600
  }

601 602 603 604 605 606 607 608 609 610

  /**
   * Gets a http kernel from the container
   *
   * @return HttpKernel
   */
  protected function getHttpKernel() {
    return $this->container->get('http_kernel');
  }

katbailey's avatar
katbailey committed
611
  /**
Crell's avatar
Crell committed
612 613
   * Overrides and eliminates this method from the parent class. Do not use.
   *
katbailey's avatar
katbailey committed
614 615 616 617 618 619 620
   * 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.
   */
621
  public function registerContainerConfiguration(LoaderInterface $loader) {
622
  }
623

624 625 626 627 628 629 630 631 632 633 634 635
  /**
   * 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;
  }

636 637 638 639 640 641 642 643 644 645 646 647 648 649
  /**
   * 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;
  }

  /**
650
   * Gets the namespaces of each enabled module.
651
   */
652 653
  protected function getModuleNamespaces($moduleFileNames) {
    $namespaces = array();
654
    foreach ($moduleFileNames as $module => $filename) {
655 656 657 658 659 660 661 662 663
      $namespaces["Drupal\\$module"] = DRUPAL_ROOT . '/' . dirname($filename) . '/lib';
    }
    return $namespaces;
  }

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