Skip to content

Commit 1ba74be

Browse files
Allow union types as datatype of parameters in @method annotations.
1 parent 6e0d18c commit 1ba74be

2 files changed

Lines changed: 41 additions & 5 deletions

File tree

src/Annotation/MethodAnnotation.php

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,14 @@ public function parameters() : array
9494
private function parseParametersString(string $parametersString) : ?array
9595
{
9696
$parameterPattern = '/^' .
97-
'((' . self::PATTERN_DATA_TYPE . ') )?' . // optional datatype plus space
97+
'(' . // optional datatype (union type allowed) plus space
98+
'(' .
99+
'(' .
100+
self::PATTERN_DATA_TYPE . preg_quote('|') .
101+
')*' .
102+
self::PATTERN_DATA_TYPE .
103+
') ' .
104+
')?' .
98105
'(' . self::PATTERN_VARIABLE_NAME . ')' . // parameter name
99106
'( = ' . // optional default value
100107
'(' .
@@ -112,19 +119,19 @@ private function parseParametersString(string $parametersString) : ?array
112119
return null;
113120
}
114121

115-
$parameterName = $matches[6];
122+
$parameterName = $matches[9];
116123
$dataType = $matches[2] ?: null;
117-
$hasDefaultValue = '' !== $matches[8];
124+
$hasDefaultValue = '' !== $matches[11];
118125
$parameters[$parameterName] = [
119126
'dataType' => $dataType,
120127
'hasDefaultValue' => $hasDefaultValue,
121128
];
122129

123130
if ($hasDefaultValue) {
124-
$parameters[$parameterName]['default'] = $matches[8];
131+
$parameters[$parameterName]['default'] = $matches[11];
125132
}
126133

127-
$parametersString = array_key_exists(12, $matches) ? $matches[12] : '';
134+
$parametersString = array_key_exists(15, $matches) ? $matches[15] : '';
128135
}
129136

130137
return $parameters;

tests/PhpUnit/Annotation/MethodAnnotationTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,35 @@ final class MethodAnnotationTest extends AbstractAnnotationTestCase
179179
[],
180180
'int|null',
181181
false,
182+
],
183+
[
184+
'foo(string|null $parameter)',
185+
'foo',
186+
[
187+
'parameter' => [
188+
'dataType' => 'string|null',
189+
'hasDefaultValue' => false,
190+
],
191+
],
192+
null,
193+
false,
194+
],
195+
[
196+
'int|null foo(string|null $parameter = "defaultValue", $secondParameter)',
197+
'foo',
198+
[
199+
'parameter' => [
200+
'dataType' => 'string|null',
201+
'hasDefaultValue' => true,
202+
'default' => '"defaultValue"',
203+
],
204+
'secondParameter' => [
205+
'dataType' => null,
206+
'hasDefaultValue' => false,
207+
]
208+
],
209+
'int|null',
210+
false,
182211
]
183212
];
184213

0 commit comments

Comments
 (0)