ModuleRouteSubscriber.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Drupal\Core\Extension\ModuleHandlerInterface;
  4. use Drupal\Core\Routing\RouteSubscriberBase;
  5. use Symfony\Component\Routing\RouteCollection;
  6. /**
  7. * A route subscriber to remove routes that depend on modules being enabled.
  8. */
  9. class ModuleRouteSubscriber extends RouteSubscriberBase {
  10. /**
  11. * The module handler.
  12. *
  13. * @var \Drupal\Core\Extension\ModuleHandlerInterface
  14. */
  15. protected $moduleHandler;
  16. /**
  17. * Constructs a ModuleRouteSubscriber object.
  18. *
  19. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  20. * The module handler.
  21. */
  22. public function __construct(ModuleHandlerInterface $module_handler) {
  23. $this->moduleHandler = $module_handler;
  24. }
  25. /**
  26. * {@inheritdoc}
  27. */
  28. protected function alterRoutes(RouteCollection $collection) {
  29. foreach ($collection as $name => $route) {
  30. if ($route->hasRequirement('_module_dependencies')) {
  31. $modules = $route->getRequirement('_module_dependencies');
  32. $explode_and = $this->explodeString($modules, '+');
  33. if (count($explode_and) > 1) {
  34. foreach ($explode_and as $module) {
  35. // If any moduleExists() call returns FALSE, remove the route and
  36. // move on to the next.
  37. if (!$this->moduleHandler->moduleExists($module)) {
  38. $collection->remove($name);
  39. continue 2;
  40. }
  41. }
  42. }
  43. else {
  44. // OR condition, exploding on ',' character.
  45. foreach ($this->explodeString($modules, ',') as $module) {
  46. if ($this->moduleHandler->moduleExists($module)) {
  47. continue 2;
  48. }
  49. }
  50. // If no modules are found, and we get this far, remove the route.
  51. $collection->remove($name);
  52. }
  53. }
  54. }
  55. }
  56. /**
  57. * Explodes a string based on a separator.
  58. *
  59. * @param string $string
  60. * The string to explode.
  61. * @param string $separator
  62. * The string separator to explode with.
  63. *
  64. * @return array
  65. * An array of exploded (and trimmed) values.
  66. */
  67. protected function explodeString($string, $separator = ',') {
  68. return array_filter(array_map('trim', explode($separator, $string)));
  69. }
  70. }