DrupalKernel.php 14.7 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 Symfony\Component\ClassLoader\UniversalClassLoader;
15
16
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
17
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
18
use Symfony\Component\HttpKernel\Kernel;
19
20
21

/**
 * The DrupalKernel class is the core of Drupal itself.
22
23
24
25
26
27
28
 *
 * 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.
29
 */
30
class DrupalKernel extends Kernel implements DrupalKernelInterface {
31

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

  /**
42
   * Holds an updated list of enabled modules.
43
   *
44
45
46
47
48
49
50
51
52
53
54
55
56
   * @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
57
   */
58
  protected $moduleData = array();
59

60
61
62
63
64
65
66
67
68
69
70
71
72
73
  /**
   * Holds a list of enabled modules and their paths.
   *
   * This is used to store module data as a container parameter so that it can
   * be retrieved for registering namespaces when using a compiled container.
   * When not using a compiled container, the namespaces get registered during
   * the process of building the container.
   *
   * @var array
   *   An associative array whose keys are module names and whose values are
   *   module paths.
   */
  protected $modulePaths = array();

74
75
76
77
78
79
80
  /**
   * PHP code storage object to use for the compiled container.
   *
   * @var \Drupal\Component\PhpStorage\PhpStorageInterface
   */
  protected $storage;

81
82
83
84
85
86
87
  /**
   * The classloader object.
   *
   * @var \Symfony\Component\ClassLoader\UniversalClassLoader
   */
  protected $classLoader;

88
89
90
91
92
93
94
  /**
   * Config storage object used for reading enabled modules configuration.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $configStorage;

95
96
97
98
99
100
101
  /**
   * The list of the classnames of the bundles in this kernel.
   *
   * @var array
   */
  protected $bundleClasses;

102
103
104
105
106
107
108
109
110
111
112
113
114
115
  /**
   * 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;

116
117
118
119
120
121
122
123
124
125
126
  /**
   * 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.
127
128
129
130
131
   * @param \Symfony\Component\ClassLoader\UniversalClassLoader $class_loader
   *   (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.
132
133
134
   * @param bool $allow_dumping
   *   (optional) FALSE to stop the container from being written to or read
   *   from disk. Defaults to TRUE.
135
   */
136
  public function __construct($environment, $debug, UniversalClassLoader $class_loader, $allow_dumping = TRUE) {
137
    parent::__construct($environment, $debug);
138
    $this->classLoader = $class_loader;
139
    $this->allowDumping = $allow_dumping;
140
141
  }

142
143
144
145
146
147
148
149
150
151
  /**
   * 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.
  }

152
153
154
155
156
157
158
159
160
  /**
   * Overrides Kernel::boot().
   */
  public function boot() {
    if ($this->booted) {
      return;
    }
    $this->initializeContainer();
    $this->booted = TRUE;
161
162
163
    if ($this->containerNeedsDumping && !$this->dumpDrupalContainer($this->container, $this->getContainerBaseClass())) {
      watchdog('DrupalKernel', 'Container cannot be written to disk');
    }
164
165
  }

166
167
  /**
   * Returns an array of available bundles.
168
169
170
   *
   * @return array
   *   The available bundles.
171
   */
172
  public function registerBundles() {
173
    $this->configStorage = BootstrapConfigStorageFactory::get();
174
    $bundles = array(
175
      new CoreBundle(),
176
    );
177
    if (!isset($this->moduleList)) {
178
      $module_list = $this->configStorage->read('system.module');
179
180
      $this->moduleList = isset($module_list['enabled']) ? $module_list['enabled'] : array();
    }
181

182
    $namespaces = $this->classLoader->getNamespaces();
183
184
185
    // We will need to store module locations in a container parameter so that
    // we can register all namespaces when using a compiled container.
    $this->modulePaths = array();
186
187
188
189
    foreach ($this->moduleList as $module => $weight) {
      // When installing new modules, the modules in the list passed to
      // updateModules() do not yet have their namespace registered.
      $namespace = 'Drupal\\' . $module;
190
      if (empty($namespaces[$namespace]) && $this->moduleData($module)) {
191
192
193
194
195
196
        $path = dirname(DRUPAL_ROOT . '/' . $this->moduleData($module)->uri) . '/lib';
        $this->modulePaths[$module] = $path;
        $this->classLoader->registerNamespace($namespace, $path);
      }
      else {
        $this->modulePaths[$module] = $namespaces[$namespace];
197
      }
katbailey's avatar
katbailey committed
198
      $camelized = ContainerBuilder::camelize($module);
199
      $class = "Drupal\\{$module}\\{$camelized}Bundle";
200
201
      if (class_exists($class)) {
        $bundles[] = new $class();
202
        $this->bundleClasses[] = $class;
203
      }
204
    }
205
206
207
208
209
210
211
    // 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;
      }
    }
212
213
    return $bundles;
  }
214

215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
  /**
   * 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) {
      // Find filenames to prime the classloader. First, find profiles.
      // Profiles might want to add a bundle too and they also can contain
      // modules.
      $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.
236
      if (($parent_profile_config = $this->configStorage->read('simpletest.settings')) && isset($parent_profile_config['parent_profile']) && $parent_profile_config['parent_profile'] != $profiles[0]) {
237
238
239
240
241
242
243
244
245
246
247
        // 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;
  }

248
249
250
  /**
   * Implements Drupal\Core\DrupalKernelInterface::updateModules().
   */
251
  public function updateModules(array $module_list, array $module_paths = array()) {
252
253
254
255
    $this->newModuleList = $module_list;
    foreach ($module_paths as $module => $path) {
      $this->moduleData[$module] = (object) array('uri' => $path);
    }
256
257
258
259
260
261
262
263
    // 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();
    }
  }
264

265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
  /**
   * 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);
  }

283
284
285
  /**
   * Initializes the service container.
   */
286
  protected function initializeContainer() {
287
    $this->container = NULL;
288
289
290
    $class = $this->getClassName();
    $cache_file = $class . '.php';

291
    if ($this->allowDumping) {
292
293
      // First, try to load.
      if (!class_exists($class, FALSE)) {
294
        $this->storage()->load($cache_file);
295
296
297
298
299
      }
      // 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;
300
301
      }
    }
302
303
304
305
306
307
308
309
310
311
312
313
    // 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);
    }
    // Second, verify that some other request -- for example on another
    // web frontend or during the installer -- changed the list of enabled
    // modules.
    if (isset($this->container)) {
314
315
316
      // All namespaces must be registered before we attempt to use any service
      // from the container.
      $namespaces = $this->classLoader->getNamespaces();
317
      $namespaces_revert = array();
318
319
      foreach ($this->container->getParameter('container.modules') as $module => $path) {
        $namespace = 'Drupal\\' . $module;
320
        if (empty($namespaces[$namespace])) {
321
          $this->classLoader->registerNamespace($namespace, $path);
322
          $namespaces_revert[$namespace] = array();
323
324
        }
      }
325
      $module_list = $this->moduleList ?: $this->container->get('config.factory')->get('system.module')->load()->get('enabled');
326
      if (array_keys((array)$module_list) !== array_keys($this->container->getParameter('container.modules'))) {
327
        unset($this->container);
328
329
330
        // Since 'container.modules' was incorrect, revert the classloader
        // registrations, and allow buildContainer() to get it right.
        $this->classLoader->registerNamespaces($namespaces_revert);
331
332
333
      }
    }

334
335
    if (!isset($this->container)) {
      $this->container = $this->buildContainer();
336
337
      if ($this->allowDumping) {
        $this->containerNeedsDumping = TRUE;
338
339
340
      }
    }

341
    $this->container->set('kernel', $this);
342
343
    // Set the class loader which was registered as a synthetic service.
    $this->container->set('class_loader', $this->classLoader);
344

345
346
    drupal_container($this->container);
  }
347

348
349
350
351
352
  /**
   * Builds the service container.
   *
   * @return ContainerBuilder The compiled service container
   */
353
  protected function buildContainer() {
354
    $this->initializeBundles();
355
    $container = $this->getContainerBuilder();
356
    $container->setParameter('container.bundles', $this->bundleClasses);
357
358
359
    $container->setParameter('container.modules', $this->modulePaths);
    // Register the class loader as a synthetic service.
    $container->register('class_loader', 'Symfony\Component\ClassLoader\UniversalClassLoader')->setSynthetic(TRUE);
360
361
    foreach ($this->bundles as $bundle) {
      $bundle->build($container);
362
    }
363
    $container->compile();
364
365
    return $container;
  }
366

367
368
369
370
371
  /**
   * Gets a new ContainerBuilder instance used to build the service container.
   *
   * @return ContainerBuilder
   */
372
  protected function getContainerBuilder() {
373
374
375
    return new ContainerBuilder(new ParameterBag($this->getKernelParameters()));
  }

376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
  /**
   * 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) {
391
    if (!$this->storage()->writeable()) {
392
393
394
395
      return FALSE;
    }
    // Cache the container.
    $dumper = new PhpDumper($container);
396
397
    $class = $this->getClassName();
    $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass));
398
    return $this->storage()->save($class . '.php', $content);
399
400
  }

katbailey's avatar
katbailey committed
401
  /**
Crell's avatar
Crell committed
402
403
   * Overrides and eliminates this method from the parent class. Do not use.
   *
katbailey's avatar
katbailey committed
404
405
406
407
408
409
410
   * 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.
   */
411
  public function registerContainerConfiguration(LoaderInterface $loader) {
412
  }
413

414
415
416
417
418
419
420
421
422
423
424
425
  /**
   * 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;
  }

426
}