-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouteParameterResolver.php
More file actions
109 lines (88 loc) · 2.72 KB
/
RouteParameterResolver.php
File metadata and controls
109 lines (88 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
declare(strict_types=1);
namespace TinyBlocks\Http\Internal\Request;
use Psr\Http\Message\ServerRequestInterface;
/**
* Resolves route parameters from a PSR-7 ServerRequestInterface in a framework-agnostic way.
*
* Supports multiple attribute formats used by popular frameworks:
* - Plain arrays (e.g., Symfony's `_route_params`)
* - Objects with accessor methods (e.g., Slim's `getArguments()`, Mezzio's `getMatchedParams()`)
* - Objects with public properties (e.g., `arguments`, `params`, `vars`)
* - Direct attributes on the request (e.g., Laravel's `getAttribute('id')`)
*/
final readonly class RouteParameterResolver
{
private const array KNOWN_ATTRIBUTE_KEYS = [
'__route__',
'_route_params',
'route',
'routing',
'routeResult',
'routeInfo'
];
private const array OBJECT_METHODS = [
'getArguments',
'getMatchedParams',
'getParameters',
'getParams'
];
private const array OBJECT_PROPERTIES = [
'arguments',
'params',
'vars',
'parameters'
];
private function __construct(private ServerRequestInterface $request)
{
}
public static function from(ServerRequestInterface $request): RouteParameterResolver
{
return new RouteParameterResolver(request: $request);
}
public function resolve(string $attributeName): array
{
$attribute = $this->request->getAttribute($attributeName);
if (is_array($attribute)) {
return $attribute;
}
if (is_object($attribute)) {
return $this->extractFromObject(object: $attribute);
}
return [];
}
public function resolveFromKnownAttributes(): array
{
foreach (self::KNOWN_ATTRIBUTE_KEYS as $key) {
$parameters = $this->resolve(attributeName: $key);
if (!empty($parameters)) {
return $parameters;
}
}
return [];
}
public function resolveDirectAttribute(string $key): mixed
{
return $this->request->getAttribute($key);
}
private function extractFromObject(object $object): array
{
foreach (self::OBJECT_METHODS as $method) {
if (method_exists($object, $method)) {
$result = $object->{$method}();
if (is_array($result)) {
return $result;
}
}
}
foreach (self::OBJECT_PROPERTIES as $property) {
if (property_exists($object, $property)) {
$value = $object->{$property};
if (is_array($value)) {
return $value;
}
}
}
return [];
}
}