I have a list of paths and I would like to identify which ones are associated to view routes.
Is there any Drupal 8 method I can use? Do I need to get all the view routes and then check which ones are associated to the paths I have?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI think the best way to do this is to use the router.route_provider service. Specifically, you may want to use RouteProvider::getRoutesByPattern()
. See the following code, adapted from code shown in joachim's comment in Get route name by path in Drupal 8.
function getViewPaths(array $paths_to_check = []): array {
/** @var \Drupal\Core\Routing\RouteProviderInterface $route_provider */
$route_provider = \Drupal::service('router.route_provider');
$view_paths = [];
foreach ($paths_to_check as $path) {
$path_route_collection = $route_provider->getRoutesByPattern($path);
foreach ($path_route_collection->all() as $route_name => $route) {
if (strpos($route_name, 'view.') === 0) {
$view_paths[] = $path;
}
}
}
return $view_paths;
}
$my_view_paths = getViewPaths([
'/about',
'/some/other/path',
'/one-more-path',
]);
Supposing the list contains paths like /node/2, /user/1, or admin/content, and you need to get the route name for those paths handled by the Views module, you could use code similar to the following one.
use Drupal\Core\Path\PathValidatorInterface;
use Drupal\Core\Url;
function _view_routes(array $paths) {
$view_routes = [];
$path_validator = \Drupal::service('path.validator');
foreach ($paths as $path) {
$view_route = '';
if ($url = $path_validator->getUrlIfValid($path)) {
$route_name = $url->getRouteName();
if (strpos($route_name, 'view.') === 0) {
$view_route = $route_name;
}
}
$view_routes[$path] = $view_route;
}
return $view_routes;
}
PathValidator::getUrlIfValid()
returns a Url
object if the path it gets as argument is valid and accessible from the currently logged-in user. To understand which paths are for pages handled by the Views module, independently from which users have access to that page, the code should be similar to the following one.
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
function _view_routes(array $paths) {
$view_routes = [];
$router = \Drupal::service('router.no_access_checks');
foreach ($paths as $path) {
try {
$match = $router->match($path);
}
catch (\Exception $e) {
// The path isn't valid or the HTTP method to access the
// path isn't allowed.
$view_routes[$path] = '';
continue;
}
$view_routes[$path] = (strpos($match['_route'], 'view.') === 0 ? $match['_route'] : '');
}
return $view_routes;
}
view path
?*.view.*
or whatever you can use?view.VIEW_ID.DISPLAY_ID