fix: extract and pass URI template variables to resource handlers (#123)

This commit is contained in:
Kyrian Obikwelu 2025-10-27 22:20:48 +01:00 • committed by GitHub
commit 55f860808c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 19 additions and 29 deletions

View file

@ -57,18 +57,17 @@ class ResourceTemplateReference extends ElementReference
public function matches(string $uri): bool
{
if (preg_match($this->uriTemplateRegex, $uri, $matches)) {
$variables = [];
foreach ($this->variableNames as $varName) {
if (isset($matches[$varName])) {
$variables[$varName] = $matches[$varName];
}
}
return 1 === preg_match($this->uriTemplateRegex, $uri);
}
return true;
}
/** @return array<string, mixed> */
public function extractVariables(string $uri): array
{
$matches = [];
return false;
preg_match($this->uriTemplateRegex, $uri, $matches);
return array_filter($matches, fn ($key) => \in_array($key, $this->variableNames), \ARRAY_FILTER_USE_KEY);
}
/**

View file

@ -65,11 +65,14 @@ final class ReadResourceHandler implements RequestHandlerInterface
'_session' => $session,
];
$result = $this->referenceHandler->handle($reference, $arguments);
if ($reference instanceof ResourceTemplateReference) {
$variables = $reference->extractVariables($uri);
$arguments = array_merge($arguments, $variables);
$result = $this->referenceHandler->handle($reference, $arguments);
$formatted = $reference->formatResult($result, $uri, $reference->resourceTemplate->mimeType);
} else {
$result = $this->referenceHandler->handle($reference, $arguments);
$formatted = $reference->formatResult($result, $uri, $reference->schema->mimeType);
}