You are here

public function VariantRouteFilter::filter in Page Manager 8

Same name and namespace in other branches
  1. 8.4 src/Routing/VariantRouteFilter.php \Drupal\page_manager\Routing\VariantRouteFilter::filter()

Ensures only one page manager route remains in the collection.

File

src/Routing/VariantRouteFilter.php, line 74
Contains \Drupal\page_manager\Routing\VariantRouteFilter.

Class

VariantRouteFilter
Filters variant routes.

Namespace

Drupal\page_manager\Routing

Code

public function filter(RouteCollection $collection, Request $request) {
  $routes = $collection
    ->all();

  // Only continue if at least one route has a page manager variant.
  if (!array_filter($routes, function (Route $route) {
    return $route
      ->hasDefault('page_manager_page_variant');
  })) {
    return $collection;
  }

  // Sort routes by variant weight.
  $routes = $this
    ->sortRoutes($routes);
  $variant_route_name = $this
    ->getVariantRouteName($routes, $request);
  foreach ($routes as $name => $route) {
    if (!$route
      ->hasDefault('page_manager_page_variant')) {
      continue;
    }

    // If this page manager route isn't the one selected, remove it.
    if ($variant_route_name !== $name) {
      unset($routes[$name]);
    }
    elseif ($overridden_route_name = $route
      ->getDefault('overridden_route_name')) {
      unset($routes[$overridden_route_name]);
    }
  }

  // Create a new route collection by iterating over the sorted routes, using
  // the overridden_route_name if available.
  $result_collection = new RouteCollection();
  foreach ($routes as $name => $route) {
    $overridden_route_name = $route
      ->getDefault('overridden_route_name') ?: $name;
    $result_collection
      ->add($overridden_route_name, $route);
  }
  return $result_collection;
}