ModuleHandler.php 25.7 KB
Newer Older
1 2 3 4 5 6 7
<?php

namespace Drupal\Core\Extension;

use Drupal\Component\Graph\Graph;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\CacheBackendInterface;
8
use Drupal\Core\Extension\Exception\UnknownExtensionException;
9 10

/**
11
 * Class that manages modules in a Drupal installation.
12 13 14 15 16 17 18 19 20 21 22 23 24
 */
class ModuleHandler implements ModuleHandlerInterface {

  /**
   * List of loaded files.
   *
   * @var array
   *   An associative array whose keys are file paths of loaded files, relative
   *   to the application's root directory.
   */
  protected $loadedFiles;

  /**
25
   * List of installed modules.
26
   *
27
   * @var \Drupal\Core\Extension\Extension[]
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
   */
  protected $moduleList;

  /**
   * Boolean indicating whether modules have been loaded.
   *
   * @var bool
   */
  protected $loaded = FALSE;

  /**
   * List of hook implementations keyed by hook name.
   *
   * @var array
   */
  protected $implementations;

45 46 47 48 49 50 51 52
  /**
   * List of hooks where the implementations have been "verified".
   *
   * @var true[]
   *   Associative array where keys are hook names.
   */
  protected $verified;

53 54 55 56 57 58 59
  /**
   * Information returned by hook_hook_info() implementations.
   *
   * @var array
   */
  protected $hookInfo;

60 61 62 63 64 65 66 67 68 69 70 71 72 73
  /**
   * Cache backend for storing module hook implementation information.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cacheBackend;

  /**
   * Whether the cache needs to be written.
   *
   * @var bool
   */
  protected $cacheNeedsWriting = FALSE;

74 75 76 77 78 79 80
  /**
   * List of alter hook implementations keyed by hook name(s).
   *
   * @var array
   */
  protected $alterFunctions;

81 82 83 84 85 86 87
  /**
   * The app root.
   *
   * @var string
   */
  protected $root;

88 89 90 91 92 93 94
  /**
   * A list of module include file keys.
   *
   * @var array
   */
  protected $includeFileKeys = [];

95 96 97
  /**
   * Constructs a ModuleHandler object.
   *
98 99
   * @param string $root
   *   The app root.
100
   * @param array $module_list
101
   *   An associative array whose keys are the names of installed modules and
102
   *   whose values are Extension class parameters. This is normally the
103
   *   %container.modules% parameter being set up by DrupalKernel.
104 105
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend for storing module hook implementation information.
106 107
   *
   * @see \Drupal\Core\DrupalKernel
108
   * @see \Drupal\Core\CoreServiceProvider
109
   */
110
  public function __construct($root, array $module_list, CacheBackendInterface $cache_backend) {
111
    $this->root = $root;
112
    $this->moduleList = [];
113
    foreach ($module_list as $name => $module) {
114
      $this->moduleList[$name] = new Extension($this->root, $module['type'], $module['pathname'], $module['filename']);
115
    }
116
    $this->cacheBackend = $cache_backend;
117 118 119
  }

  /**
120
   * {@inheritdoc}
121 122 123 124 125 126 127
   */
  public function load($name) {
    if (isset($this->loadedFiles[$name])) {
      return TRUE;
    }

    if (isset($this->moduleList[$name])) {
128
      $this->moduleList[$name]->load();
129 130 131 132 133 134 135
      $this->loadedFiles[$name] = TRUE;
      return TRUE;
    }
    return FALSE;
  }

  /**
136
   * {@inheritdoc}
137 138 139
   */
  public function loadAll() {
    if (!$this->loaded) {
140 141
      foreach ($this->moduleList as $name => $module) {
        $this->load($name);
142 143 144 145 146 147
      }
      $this->loaded = TRUE;
    }
  }

  /**
148
   * {@inheritdoc}
149 150 151 152 153 154 155
   */
  public function reload() {
    $this->loaded = FALSE;
    $this->loadAll();
  }

  /**
156
   * {@inheritdoc}
157 158 159 160 161 162
   */
  public function isLoaded() {
    return $this->loaded;
  }

  /**
163
   * {@inheritdoc}
164 165 166 167 168
   */
  public function getModuleList() {
    return $this->moduleList;
  }

169 170 171 172 173 174 175
  /**
   * {@inheritdoc}
   */
  public function getModule($name) {
    if (isset($this->moduleList[$name])) {
      return $this->moduleList[$name];
    }
176
    throw new UnknownExtensionException(sprintf('The module %s does not exist.', $name));
177 178
  }

179
  /**
180
   * {@inheritdoc}
181
   */
182
  public function setModuleList(array $module_list = []) {
183
    $this->moduleList = $module_list;
184 185 186
    // Reset the implementations, so a new call triggers a reloading of the
    // available hooks.
    $this->resetImplementations();
187 188
  }

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
  /**
   * {@inheritdoc}
   */
  public function addModule($name, $path) {
    $this->add('module', $name, $path);
  }

  /**
   * {@inheritdoc}
   */
  public function addProfile($name, $path) {
    $this->add('profile', $name, $path);
  }

  /**
   * Adds a module or profile to the list of currently active modules.
   *
   * @param string $type
   *   The extension type; either 'module' or 'profile'.
   * @param string $name
   *   The module name; e.g., 'node'.
   * @param string $path
   *   The module path; e.g., 'core/modules/node'.
   */
  protected function add($type, $name, $path) {
    $pathname = "$path/$name.info.yml";
215 216
    $filename = file_exists($this->root . "/$path/$name.$type") ? "$name.$type" : NULL;
    $this->moduleList[$name] = new Extension($this->root, $type, $pathname, $filename);
217 218 219
    $this->resetImplementations();
  }

220
  /**
221
   * {@inheritdoc}
222 223
   */
  public function buildModuleDependencies(array $modules) {
224
    foreach ($modules as $module) {
225
      $graph[$module->getName()]['edges'] = [];
226 227
      if (isset($module->info['dependencies']) && is_array($module->info['dependencies'])) {
        foreach ($module->info['dependencies'] as $dependency) {
228
          $dependency_data = static::parseDependency($dependency);
229
          $graph[$module->getName()]['edges'][$dependency_data['name']] = $dependency_data;
230 231 232 233 234 235
        }
      }
    }
    $graph_object = new Graph($graph);
    $graph = $graph_object->searchAndSort();
    foreach ($graph as $module_name => $data) {
236 237
      $modules[$module_name]->required_by = isset($data['reverse_paths']) ? $data['reverse_paths'] : [];
      $modules[$module_name]->requires = isset($data['paths']) ? $data['paths'] : [];
238 239 240 241 242 243
      $modules[$module_name]->sort = $data['weight'];
    }
    return $modules;
  }

  /**
244
   * {@inheritdoc}
245 246 247 248 249 250
   */
  public function moduleExists($module) {
    return isset($this->moduleList[$module]);
  }

  /**
251
   * {@inheritdoc}
252 253 254 255 256 257 258 259
   */
  public function loadAllIncludes($type, $name = NULL) {
    foreach ($this->moduleList as $module => $filename) {
      $this->loadInclude($module, $type, $name);
    }
  }

  /**
260
   * {@inheritdoc}
261 262 263 264
   */
  public function loadInclude($module, $type, $name = NULL) {
    if ($type == 'install') {
      // Make sure the installation API is available
265
      include_once $this->root . '/core/includes/install.inc';
266 267 268
    }

    $name = $name ?: $module;
269 270 271 272
    $key = $type . ':' . $module . ':' . $name;
    if (isset($this->includeFileKeys[$key])) {
      return $this->includeFileKeys[$key];
    }
273
    if (isset($this->moduleList[$module])) {
274
      $file = $this->root . '/' . $this->moduleList[$module]->getPath() . "/$name.$type";
275 276
      if (is_file($file)) {
        require_once $file;
277
        $this->includeFileKeys[$key] = $file;
278 279
        return $file;
      }
280 281 282
      else {
        $this->includeFileKeys[$key] = FALSE;
      }
283 284 285 286
    }
    return FALSE;
  }

287
  /**
288
   * {@inheritdoc}
289 290
   */
  public function getHookInfo() {
291 292 293 294 295 296 297 298
    if (!isset($this->hookInfo)) {
      if ($cache = $this->cacheBackend->get('hook_info')) {
        $this->hookInfo = $cache->data;
      }
      else {
        $this->buildHookInfo();
        $this->cacheBackend->set('hook_info', $this->hookInfo);
      }
299
    }
300 301 302 303 304 305 306 307 308
    return $this->hookInfo;
  }

  /**
   * Builds hook_hook_info() information.
   *
   * @see \Drupal\Core\Extension\ModuleHandler::getHookInfo()
   */
  protected function buildHookInfo() {
309
    $this->hookInfo = [];
310 311
    // Make sure that the modules are loaded before checking.
    $this->reload();
312
    // $this->invokeAll() would cause an infinite recursion.
313 314 315 316 317 318 319 320 321 322 323
    foreach ($this->moduleList as $module => $filename) {
      $function = $module . '_hook_info';
      if (function_exists($function)) {
        $result = $function();
        if (isset($result) && is_array($result)) {
          $this->hookInfo = NestedArray::mergeDeep($this->hookInfo, $result);
        }
      }
    }
  }

324
  /**
325
   * {@inheritdoc}
326 327 328 329 330 331 332
   */
  public function getImplementations($hook) {
    $implementations = $this->getImplementationInfo($hook);
    return array_keys($implementations);
  }

  /**
333 334 335 336 337 338 339 340 341 342 343
   * {@inheritdoc}
   */
  public function writeCache() {
    if ($this->cacheNeedsWriting) {
      $this->cacheBackend->set('module_implements', $this->implementations);
      $this->cacheNeedsWriting = FALSE;
    }
  }

  /**
   * {@inheritdoc}
344 345 346 347 348
   */
  public function resetImplementations() {
    $this->implementations = NULL;
    $this->hookInfo = NULL;
    $this->alterFunctions = NULL;
349 350 351 352 353 354 355 356 357 358 359
    // We maintain a persistent cache of hook implementations in addition to the
    // static cache to avoid looping through every module and every hook on each
    // request. Benchmarks show that the benefit of this caching outweighs the
    // additional database hit even when using the default database caching
    // backend and only a small number of modules are enabled. The cost of the
    // $this->cacheBackend->get() is more or less constant and reduced further
    // when non-database caching backends are used, so there will be more
    // significant gains when a large number of modules are installed or hooks
    // invoked, since this can quickly lead to
    // \Drupal::moduleHandler()->implementsHook() being called several thousand
    // times per request.
360
    $this->cacheBackend->set('module_implements', []);
361
    $this->cacheBackend->delete('hook_info');
362 363 364
  }

  /**
365
   * {@inheritdoc}
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
   */
  public function implementsHook($module, $hook) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      return TRUE;
    }
    // If the hook implementation does not exist, check whether it lives in an
    // optional include file registered via hook_hook_info().
    $hook_info = $this->getHookInfo();
    if (isset($hook_info[$hook]['group'])) {
      $this->loadInclude($module, 'inc', $module . '.' . $hook_info[$hook]['group']);
      if (function_exists($function)) {
        return TRUE;
      }
    }
    return FALSE;
  }

384
  /**
385
   * {@inheritdoc}
386
   */
387
  public function invoke($module, $hook, array $args = []) {
388 389 390 391 392 393 394
    if (!$this->implementsHook($module, $hook)) {
      return;
    }
    $function = $module . '_' . $hook;
    return call_user_func_array($function, $args);
  }

395
  /**
396
   * {@inheritdoc}
397
   */
398 399
  public function invokeAll($hook, array $args = []) {
    $return = [];
400 401 402
    $implementations = $this->getImplementations($hook);
    foreach ($implementations as $module) {
      $function = $module . '_' . $hook;
403 404 405 406 407 408
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = NestedArray::mergeDeep($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
409 410 411 412 413 414
      }
    }

    return $return;
  }

415 416 417
  /**
   * {@inheritdoc}
   */
418
  public function invokeDeprecated($description, $module, $hook, array $args = []) {
419 420 421 422 423 424 425 426
    $result = $this->invoke($module, $hook, $args);
    $this->triggerDeprecationError($description, $hook);
    return $result;
  }

  /**
   * {@inheritdoc}
   */
427
  public function invokeAllDeprecated($description, $hook, array $args = []) {
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
    $result = $this->invokeAll($hook, $args);
    $this->triggerDeprecationError($description, $hook);
    return $result;
  }

  /**
   * Triggers an E_USER_DEPRECATED error if any module implements the hook.
   *
   * @param string $description
   *   Helpful text describing what to do instead of implementing this hook.
   * @param string $hook
   *   The name of the hook.
   */
  private function triggerDeprecationError($description, $hook) {
    $modules = array_keys($this->getImplementationInfo($hook));
    if (!empty($modules)) {
      $message = 'The deprecated hook hook_' . $hook . '() is implemented in these functions: ';
      $implementations = array_map(function ($module) use ($hook) {
        return $module . '_' . $hook . '()';
      }, $modules);
      @trigger_error($message . implode(', ', $implementations) . '. ' . $description, E_USER_DEPRECATED);
    }
  }

452
  /**
453
   * {@inheritdoc}
454 455 456 457 458 459 460 461 462 463 464
   */
  public function alter($type, &$data, &$context1 = NULL, &$context2 = NULL) {
    // Most of the time, $type is passed as a string, so for performance,
    // normalize it to that. When passed as an array, usually the first item in
    // the array is a generic type, and additional items in the array are more
    // specific variants of it, as in the case of array('form', 'form_FORM_ID').
    if (is_array($type)) {
      $cid = implode(',', $type);
      $extra_types = $type;
      $type = array_shift($extra_types);
      // Allow if statements in this function to use the faster isset() rather
465 466
      // than !empty() both when $type is passed as a string, or as an array
      // with one item.
467 468 469 470 471 472 473 474 475 476 477 478
      if (empty($extra_types)) {
        unset($extra_types);
      }
    }
    else {
      $cid = $type;
    }

    // Some alter hooks are invoked many times per page request, so store the
    // list of functions to call, and on subsequent calls, iterate through them
    // quickly.
    if (!isset($this->alterFunctions[$cid])) {
479
      $this->alterFunctions[$cid] = [];
480 481 482 483
      $hook = $type . '_alter';
      $modules = $this->getImplementations($hook);
      if (!isset($extra_types)) {
        // For the more common case of a single hook, we do not need to call
484 485
        // function_exists(), since $this->getImplementations() returns only
        // modules with implementations.
486 487 488 489 490 491 492
        foreach ($modules as $module) {
          $this->alterFunctions[$cid][] = $module . '_' . $hook;
        }
      }
      else {
        // For multiple hooks, we need $modules to contain every module that
        // implements at least one of them.
493
        $extra_modules = [];
494 495 496 497 498
        foreach ($extra_types as $extra_type) {
          $extra_modules = array_merge($extra_modules, $this->getImplementations($extra_type . '_alter'));
        }
        // If any modules implement one of the extra hooks that do not implement
        // the primary hook, we need to add them to the $modules array in their
499 500 501 502 503
        // appropriate order. $this->getImplementations() can only return
        // ordered implementations of a single hook. To get the ordered
        // implementations of multiple hooks, we mimic the
        // $this->getImplementations() logic of first ordering by
        // $this->getModuleList(), and then calling
504 505 506 507
        // $this->alter('module_implements').
        if (array_diff($extra_modules, $modules)) {
          // Merge the arrays and order by getModuleList().
          $modules = array_intersect(array_keys($this->moduleList), array_merge($modules, $extra_modules));
508 509 510
          // Since $this->getImplementations() already took care of loading the
          // necessary include files, we can safely pass FALSE for the array
          // values.
511 512 513
          $implementations = array_fill_keys($modules, FALSE);
          // Let modules adjust the order solely based on the primary hook. This
          // ensures the same module order regardless of whether this if block
514 515 516
          // runs. Calling $this->alter() recursively in this way does not
          // result in an infinite loop, because this call is for a single
          // $type, so we won't end up in this code block again.
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
          $this->alter('module_implements', $implementations, $hook);
          $modules = array_keys($implementations);
        }
        foreach ($modules as $module) {
          // Since $modules is a merged array, for any given module, we do not
          // know whether it has any particular implementation, so we need a
          // function_exists().
          $function = $module . '_' . $hook;
          if (function_exists($function)) {
            $this->alterFunctions[$cid][] = $function;
          }
          foreach ($extra_types as $extra_type) {
            $function = $module . '_' . $extra_type . '_alter';
            if (function_exists($function)) {
              $this->alterFunctions[$cid][] = $function;
            }
          }
        }
      }
    }

    foreach ($this->alterFunctions[$cid] as $function) {
      $function($data, $context1, $context2);
    }
  }

543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
  /**
   * {@inheritdoc}
   */
  public function alterDeprecated($description, $type, &$data, &$context1 = NULL, &$context2 = NULL) {
    // Invoke the alter hook. This has the side effect of populating
    // $this->alterFunctions.
    $this->alter($type, $data, $context1, $context2);
    // The $type parameter can be an array. alter() will deal with this
    // internally, but we have to extract the proper $cid in order to discover
    // implementations.
    $cid = $type;
    if (is_array($type)) {
      $cid = implode(',', $type);
      $extra_types = $type;
      $type = array_shift($extra_types);
    }
    if (!empty($this->alterFunctions[$cid])) {
      $message = 'The deprecated alter hook hook_' . $type . '_alter() is implemented in these functions: ' . implode(', ', $this->alterFunctions[$cid]) . '.';
      @trigger_error($message . ' ' . $description, E_USER_DEPRECATED);
    }
  }

565 566 567 568 569 570
  /**
   * Provides information about modules' implementations of a hook.
   *
   * @param string $hook
   *   The name of the hook (e.g. "help" or "menu").
   *
571
   * @return mixed[]
572
   *   An array whose keys are the names of the modules which are implementing
573 574 575
   *   this hook and whose values are either a string identifying a file in
   *   which the implementation is to be found, or FALSE, if the implementation
   *   is in the module file.
576 577
   */
  protected function getImplementationInfo($hook) {
578
    if (!isset($this->implementations)) {
579 580
      $this->implementations = [];
      $this->verified = [];
581 582 583 584 585 586 587 588
      if ($cache = $this->cacheBackend->get('module_implements')) {
        $this->implementations = $cache->data;
      }
    }
    if (!isset($this->implementations[$hook])) {
      // The hook is not cached, so ensure that whether or not it has
      // implementations, the cache is updated at the end of the request.
      $this->cacheNeedsWriting = TRUE;
589
      // Discover implementations.
590
      $this->implementations[$hook] = $this->buildImplementationInfo($hook);
591 592
      // Implementations are always "verified" as part of the discovery.
      $this->verified[$hook] = TRUE;
593
    }
594 595 596 597 598
    elseif (!isset($this->verified[$hook])) {
      if (!$this->verifyImplementations($this->implementations[$hook], $hook)) {
        // One or more of the implementations did not exist and need to be
        // removed in the cache.
        $this->cacheNeedsWriting = TRUE;
599
      }
600
      $this->verified[$hook] = TRUE;
601 602 603 604 605 606 607 608 609 610
    }
    return $this->implementations[$hook];
  }

  /**
   * Builds hook implementation information for a given hook name.
   *
   * @param string $hook
   *   The name of the hook (e.g. "help" or "menu").
   *
611
   * @return mixed[]
612
   *   An array whose keys are the names of the modules which are implementing
613 614 615 616 617 618 619
   *   this hook and whose values are either a string identifying a file in
   *   which the implementation is to be found, or FALSE, if the implementation
   *   is in the module file.
   *
   * @throws \RuntimeException
   *   Exception thrown when an invalid implementation is added by
   *   hook_module_implements_alter().
620 621 622 623
   *
   * @see \Drupal\Core\Extension\ModuleHandler::getImplementationInfo()
   */
  protected function buildImplementationInfo($hook) {
624
    $implementations = [];
625
    $hook_info = $this->getHookInfo();
626
    foreach ($this->moduleList as $module => $extension) {
627
      $include_file = isset($hook_info[$hook]['group']) && $this->loadInclude($module, 'inc', $module . '.' . $hook_info[$hook]['group']);
628
      // Since $this->implementsHook() may needlessly try to load the include
629 630
      // file again, function_exists() is used directly here.
      if (function_exists($module . '_' . $hook)) {
631
        $implementations[$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
632 633
      }
    }
634
    // Allow modules to change the weight of specific implementations, but avoid
635 636
    // an infinite loop.
    if ($hook != 'module_implements_alter') {
637 638 639 640 641 642 643
      // Remember the original implementations, before they are modified with
      // hook_module_implements_alter().
      $implementations_before = $implementations;
      // Verify implementations that were added or modified.
      $this->alter('module_implements', $implementations, $hook);
      // Verify new or modified implementations.
      foreach (array_diff_assoc($implementations, $implementations_before) as $module => $group) {
644 645
        // If an implementation of hook_module_implements_alter() changed or
        // added a group, the respective file needs to be included.
646 647 648 649 650
        if ($group) {
          $this->loadInclude($module, 'inc', "$module.$group");
        }
        // If a new implementation was added, verify that the function exists.
        if (!function_exists($module . '_' . $hook)) {
651
          throw new \RuntimeException("An invalid implementation {$module}_{$hook} was added by hook_module_implements_alter()");
652 653
        }
      }
654
    }
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
    return $implementations;
  }

  /**
   * Verifies an array of implementations loaded from the cache, by including
   * the lazy-loaded $module.$group.inc, and checking function_exists().
   *
   * @param string[] $implementations
   *   Implementation "group" by module name.
   * @param string $hook
   *   The hook name.
   *
   * @return bool
   *   TRUE, if all implementations exist.
   *   FALSE, if one or more implementations don't exist and need to be removed
   *     from the cache.
   */
  protected function verifyImplementations(&$implementations, $hook) {
    $all_valid = TRUE;
    foreach ($implementations as $module => $group) {
      // If this hook implementation is stored in a lazy-loaded file, include
      // that file first.
      if ($group) {
        $this->loadInclude($module, 'inc', "$module.$group");
      }
      // It is possible that a module removed a hook implementation without
      // the implementations cache being rebuilt yet, so we check whether the
      // function exists on each request to avoid undefined function errors.
      // Since ModuleHandler::implementsHook() may needlessly try to
      // load the include file again, function_exists() is used directly here.
      if (!function_exists($module . '_' . $hook)) {
        // Clear out the stale implementation from the cache and force a cache
        // refresh to forget about no longer existing hook implementations.
        unset($implementations[$module]);
        // One of the implementations did not exist and needs to be removed in
        // the cache.
        $all_valid = FALSE;
      }
    }
    return $all_valid;
695 696 697 698 699 700
  }

  /**
   * Parses a dependency for comparison by drupal_check_incompatibility().
   *
   * @param $dependency
701 702 703 704 705 706
   *   A dependency string, which specifies a module dependency, and optionally
   *   the project it comes from and versions that are supported. Supported
   *   formats include:
   *   - 'module'
   *   - 'project:module'
   *   - 'project:module (>=version, version)'
707 708 709 710 711 712 713 714 715 716 717 718 719
   *
   * @return
   *   An associative array with three keys:
   *   - 'name' includes the name of the thing to depend on (e.g. 'foo').
   *   - 'original_version' contains the original version string (which can be
   *     used in the UI for reporting incompatibilities).
   *   - 'versions' is a list of associative arrays, each containing the keys
   *     'op' and 'version'. 'op' can be one of: '=', '==', '!=', '<>', '<',
   *     '<=', '>', or '>='. 'version' is one piece like '4.5-beta3'.
   *   Callers should pass this structure to drupal_check_incompatibility().
   *
   * @see drupal_check_incompatibility()
   */
720
  public static function parseDependency($dependency) {
721
    $value = [];
722 723 724 725 726
    // Split out the optional project name.
    if (strpos($dependency, ':') !== FALSE) {
      list($project_name, $dependency) = explode(':', $dependency);
      $value['project'] = $project_name;
    }
727 728
    // We use named subpatterns and support every op that version_compare
    // supports. Also, op is optional and defaults to equals.
729
    $p_op = '(?<operation>!=|==|=|<|<=|>|>=|<>)?';
730
    // Core version is always optional: 8.x-2.x and 2.x is treated the same.
731
    $p_core = '(?:' . preg_quote(\Drupal::CORE_COMPATIBILITY) . '-)?';
732
    $p_major = '(?<major>\d+)';
733
    // By setting the minor version to x, branches can be matched.
734
    $p_minor = '(?<minor>(?:\d+|x)(?:-[A-Za-z]+\d+)?)';
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
    $parts = explode('(', $dependency, 2);
    $value['name'] = trim($parts[0]);
    if (isset($parts[1])) {
      $value['original_version'] = ' (' . $parts[1];
      foreach (explode(',', $parts[1]) as $version) {
        if (preg_match("/^\s*$p_op\s*$p_core$p_major\.$p_minor/", $version, $matches)) {
          $op = !empty($matches['operation']) ? $matches['operation'] : '=';
          if ($matches['minor'] == 'x') {
            // Drupal considers "2.x" to mean any version that begins with
            // "2" (e.g. 2.0, 2.9 are all "2.x"). PHP's version_compare(),
            // on the other hand, treats "x" as a string; so to
            // version_compare(), "2.x" is considered less than 2.0. This
            // means that >=2.x and <2.x are handled by version_compare()
            // as we need, but > and <= are not.
            if ($op == '>' || $op == '<=') {
              $matches['major']++;
            }
            // Equivalence can be checked by adding two restrictions.
            if ($op == '=' || $op == '==') {
754
              $value['versions'][] = ['op' => '<', 'version' => ($matches['major'] + 1) . '.x'];
755 756 757
              $op = '>=';
            }
          }
758
          $value['versions'][] = ['op' => $op, 'version' => $matches['major'] . '.' . $matches['minor']];
759 760 761 762 763
        }
      }
    }
    return $value;
  }
764

765 766 767 768
  /**
   * {@inheritdoc}
   */
  public function getModuleDirectories() {
769
    $dirs = [];
770
    foreach ($this->getModuleList() as $name => $module) {
771
      $dirs[$name] = $this->root . '/' . $module->getPath();
772 773 774
    }
    return $dirs;
  }
775

776 777 778 779
  /**
   * {@inheritdoc}
   */
  public function getName($module) {
780
    return \Drupal::service('extension.list.module')->getName($module);
781
  }
782

783
}