3 namespace Drupal\Core\EventSubscriber;
5 use Drupal\Core\Extension\ModuleHandlerInterface;
6 use Drupal\Core\Routing\RouteSubscriberBase;
7 use Symfony\Component\Routing\RouteCollection;
10 * A route subscriber to remove routes that depend on modules being enabled.
12 class ModuleRouteSubscriber extends RouteSubscriberBase {
17 * @var \Drupal\Core\Extension\ModuleHandlerInterface
19 protected $moduleHandler;
22 * Constructs a ModuleRouteSubscriber object.
24 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
27 public function __construct(ModuleHandlerInterface $module_handler) {
28 $this->moduleHandler = $module_handler;
34 protected function alterRoutes(RouteCollection $collection) {
35 foreach ($collection as $name => $route) {
36 if ($route->hasRequirement('_module_dependencies')) {
37 $modules = $route->getRequirement('_module_dependencies');
39 $explode_and = $this->explodeString($modules, '+');
40 if (count($explode_and) > 1) {
41 foreach ($explode_and as $module) {
42 // If any moduleExists() call returns FALSE, remove the route and
43 // move on to the next.
44 if (!$this->moduleHandler->moduleExists($module)) {
45 $collection->remove($name);
51 // OR condition, exploding on ',' character.
52 foreach ($this->explodeString($modules, ',') as $module) {
53 if ($this->moduleHandler->moduleExists($module)) {
57 // If no modules are found, and we get this far, remove the route.
58 $collection->remove($name);
65 * Explodes a string based on a separator.
67 * @param string $string
68 * The string to explode.
69 * @param string $separator
70 * The string separator to explode with.
73 * An array of exploded (and trimmed) values.
75 protected function explodeString($string, $separator = ',') {
76 return array_filter(array_map('trim', explode($separator, $string)));