Skip to content

Commit 3da360a

Browse files
Allow applying the Param attribute at parameter level
1 parent 83677d5 commit 3da360a

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

doc/Param.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ If the function or method has more than one parameter, the types for the differe
1616

1717
If any of the parameters is variadic, the `...` operator needs to be listed with the type, not the argument name.
1818

19+
You can also directly apply the attribute to any of the method/function parameters. In that case, the name of the argument is optional and, if added, should match the name of the parameter to which it is applied.
20+
1921
## Example usage
2022

2123
```php
@@ -58,5 +60,12 @@ class ParamExample
5860
public function variadicMethodParam(...$params)
5961
{
6062
}
63+
64+
// Attribute applied at parameter level
65+
public function paramOnParam(
66+
#[Param('string[]')]
67+
array $param
68+
) {
69+
}
6170
}
6271
```

src/Param.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#[Attribute(
1010
Attribute::TARGET_METHOD |
1111
Attribute::TARGET_FUNCTION |
12+
Attribute::TARGET_PARAMETER |
1213
Attribute::IS_REPEATABLE
1314
)]
1415
final class Param

tests/ParamTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@ public function testVariadicMethodParam(): void
5454
$this->assertEquals(['params' => 'string ...'], $this->variadicMethodParam('Test'));
5555
}
5656

57+
public function testParamOnParam(): void
58+
{
59+
$this->assertEquals(['param' => 'string'], $this->paramOnParam('Test'));
60+
}
61+
5762
#[Param(param: 'string')]
5863
private function methodParam(string $param): array
5964
{
@@ -94,6 +99,13 @@ private function variadicMethodParam(string ...$params): array
9499
return $this->getParams(__FUNCTION__);
95100
}
96101

102+
private function paramOnParam(
103+
#[Param('string')]
104+
string $param
105+
): array {
106+
return $this->getParams(__FUNCTION__);
107+
}
108+
97109
private function getParams(string $functionName): array
98110
{
99111
$reflection = new ReflectionMethod($this, $functionName);
@@ -112,6 +124,20 @@ public static function getParamsFromReflection(
112124
}
113125
}
114126

127+
$parameters = $reflection->getParameters();
128+
foreach ($parameters as $parameter) {
129+
$attributes = $parameter->getAttributes();
130+
foreach ($attributes as $attribute) {
131+
if ($attribute->getName() === Param::class) {
132+
$attribute->newInstance();
133+
$arguments = $attribute->getArguments();
134+
$argument = $arguments[array_key_first($arguments)];
135+
$params[$parameter->name] = $argument;
136+
;
137+
}
138+
}
139+
}
140+
115141
return $params;
116142
}
117143
}

0 commit comments

Comments
 (0)