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