Skip to content

Commit

Permalink
Give more priority for exact path against regex match
Browse files Browse the repository at this point in the history
  • Loading branch information
bastien-phi committed Mar 1, 2024
1 parent caa8fb7 commit 3e53d33
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/Middleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,21 +125,36 @@ protected function pathItem(Route $route, string $requestMethod): array

$this->version = $openapi->openapi;

$pathMatches = false;
$partialMatch = null;

foreach ($openapi->paths as $path => $pathItem) {
$resolvedPath = $this->resolvePath($path);
if (Str::match($route->getCompiled()->getRegex(), $resolvedPath) !== '') {
$methods = array_keys($pathItem->getOperations());
$methods = array_keys($pathItem->getOperations());

if ($resolvedPath === $requestPath) {
$pathMatches = true;
// Check if the method exists for this path, and if so return the full PathItem
if (in_array(strtolower($requestMethod), $methods, true)) {
return [$resolvedPath, $pathItem];
}
}

throw new InvalidPathException("[{$requestMethod}] not a valid method for [{$requestPath}].", 405);
if (Str::match($route->getCompiled()->getRegex(), $resolvedPath) !== '') {
$pathMatches = true;
if (in_array(strtolower($requestMethod), $methods, true)) {
$partialMatch = [$resolvedPath, $pathItem];
}
}
}

throw new InvalidPathException("Path [{$requestMethod} {$requestPath}] not found in spec.", 404);
if ($partialMatch !== null) {
return $partialMatch;
}

throw $pathMatches
? throw new InvalidPathException("[{$requestMethod}] not a valid method for [{$requestPath}].", 405)
: new InvalidPathException("Path [{$requestMethod} {$requestPath}] not found in spec.", 404);
}

protected function resolvePath(string $path): string
Expand Down
30 changes: 30 additions & 0 deletions tests/Fixtures/Test.v1.json
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,36 @@
"operationId": "get-users-user"
}
},
"/users/me": {
"get": {
"summary": "Get current user",
"tags": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"email": {
"type": "string"
}
}
}
}
}
}
},
"operationId": "get-users-user"
}
},
"/users-by-id/{user}": {
"parameters": [
{
Expand Down

0 comments on commit 3e53d33

Please sign in to comment.