Route from a custom module :
custom.route:
path: /the/{id}/path
Hypothetical url : /the/53/path
The goal is the get the id value ("53").
So far, I managed to get the route name from the url with
$url = "/the/53/path";
$route_provider = \Drupal::service('router.route_provider');
$found_routes = $route_provider->getRoutesByPattern($url);
In $found_routes, I can find the "custom.route" route name.
Now, I need to find the parameters value, but I can't achieve it.
use Drupal\Core\Routing\RouteMatch;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
/**
* Returns the parameters of a given URL.
*
* @param string $url
* The URL.
* @param string $route_name
* The name of the route.
*
* @return array
* An array of parameters for the URL.
*/
function getUrlParameters(string $url, string $route_name): array {
// Create a URL object from the given URL string.
$url_object = Url::fromUri('base:/' . ltrim($url, '/'));
// Create a request object from the URL object.
$request = \Drupal::requestStack()->getMasterRequest();
$request = $request->duplicate();
$request->setMethod('GET');
$request->attributes->set('_route', $route_name);
$url_object->mergeOptions(['query' => $request->query->all()]);
$request->server->set('REQUEST_URI', $url_object->toString());
// Use the route matcher to get the route matching the URL.
/** @var \Drupal\Core\Routing\RouteMatchInterface $route_match */
$route_match = RouteMatch::createFromRequest($request, \Drupal::service('router'));
// Return the parameters of the URL.
return $route_match->getParameters()->all();
}