You are here

class RouteSubscriber in Custom Permissions 8

Same name and namespace in other branches
  1. 8.2 src/Routing/RouteSubscriber.php \Drupal\config_perms\Routing\RouteSubscriber

Class RouteSubscriber.

@package Drupal\config_perms\Routing Listens to the dynamic route events.

Hierarchy

Expanded class hierarchy of RouteSubscriber

1 string reference to 'RouteSubscriber'
config_perms.services.yml in ./config_perms.services.yml
config_perms.services.yml
1 service uses RouteSubscriber
config_perms.route_subscriber in ./config_perms.services.yml
Drupal\config_perms\Routing\RouteSubscriber

File

src/Routing/RouteSubscriber.php, line 15

Namespace

Drupal\config_perms\Routing
View source
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    $custom_perms = CustomPermsEntity::loadMultiple();
    foreach ($custom_perms as $custom_perm) {
      if ($custom_perm
        ->getStatus()) {
        $paths = $this
          ->configPermsParsePath($custom_perm
          ->getPath());
        foreach ($paths as $path) {
          $path = $path[0] == '/' ? $path : '/' . $path;
          $url_object = \Drupal::service('path.validator')
            ->getUrlIfValidWithoutAccessCheck($path);
          if ($url_object) {
            $route_name = $url_object
              ->getRouteName();
            if ($route = $collection
              ->get($route_name)) {
              $route
                ->setRequirement('_permission', $custom_perm
                ->label());
            }
          }
        }
      }
    }
  }

  /**
   * Custom permission paths to array of paths.
   *
   * @param string $path
   *   Path(s) given by the user.
   *
   * @return array|string
   *   Implode paths in array of strings.
   */
  public function configPermsParsePath($path) {
    if (is_array($path)) {
      $string = implode("\n", $path);
      return $string;
    }
    else {
      $path = str_replace([
        "\r\n",
        "\n\r",
        "\n",
        "\r",
      ], "\n", $path);
      $parts = explode("\n", $path);
      return $parts;
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
RouteSubscriber::alterRoutes protected function Alters existing routes for a specific collection. Overrides RouteSubscriberBase::alterRoutes
RouteSubscriber::configPermsParsePath public function Custom permission paths to array of paths.
RouteSubscriberBase::getSubscribedEvents public static function Returns an array of event names this subscriber wants to listen to. 5
RouteSubscriberBase::onAlterRoutes public function Delegates the route altering to self::alterRoutes(). 1