>|null templated uri => parameter names */ private static ?array $canonical = null; public static function normalize(Route $route, ReflectionFunctionAbstract $method): string { $uri = UrlParamsNormalizer::normalizeParameterNamesInRouteUri($route, $method); $names = self::canonical()[self::template($route->uri)] ?? null; if ($names === null) { return $uri; } $position = 0; return preg_replace_callback( '/\{(\w+)(\??)\}/', function (array $match) use ($names, &$position): string { return '{'.($names[$position++] ?? $match[1]).$match[2].'}'; }, $uri, ) ?? $uri; } /** * For each parameter position on a shared path, the name most of its routes get from * Scribe. Ties prefer a descriptive name over a bare `id`, then the route's own name. * * @return array> */ private static function canonical(): array { if (self::$canonical !== null) { return self::$canonical; } $candidates = []; foreach (Router::getRoutes()->getRoutes() as $route) { try { $method = Utils::getReflectedRouteMethod(Utils::getRouteClassAndMethodNames($route)); } catch (Throwable) { continue; } $uri = UrlParamsNormalizer::normalizeParameterNamesInRouteUri($route, $method); preg_match_all('/\{(\w+)\??\}/', $uri, $normalized); preg_match_all('/\{(\w+)[^}]*\}/', $route->uri, $raw); foreach ($normalized[1] as $position => $name) { $candidates[self::template($route->uri)][$position][$name] ??= ['count' => 0, 'raw' => $raw[1][$position] ?? null]; $candidates[self::template($route->uri)][$position][$name]['count']++; } } self::$canonical = []; foreach ($candidates as $template => $positions) { $chosen = []; foreach ($positions as $names) { uksort($names, fn (string $a, string $b): int => [ $names[$b]['count'], $b !== 'id', $b === $names[$b]['raw'], $a, ] <=> [ $names[$a]['count'], $a !== 'id', $a === $names[$a]['raw'], $b, ]); $chosen[] = array_key_first($names); } self::$canonical[$template] = $chosen; } return self::$canonical; } private static function template(string $uri): string { return preg_replace('/\{[^}]+\}/', '{}', mb_trim($uri, '/')) ?? $uri; } }