Support braces in types for @return

In this change, I have introduced a miniature automaton-light to parse
the type from the @return body. This will prevent issues with people
using generics and other unsupported forms of types.

This change does _not_ allow for the use of Generics or similar; the
TypeResolver will still fail to resolve this type. This will remove a
breaking issue in consuming applications where a runtime exception used
to be thrown.

Please note that this change is only for @return; other tags still need
to be done. This will resolve issue #186
This commit is contained in:
Mike van Riel
2019-12-27 20:18:32 +01:00
parent c19ab7ef57
commit 19dd184a2b
2 changed files with 63 additions and 4 deletions
+28 -4
View File
@@ -50,11 +50,10 @@ final class Return_ extends BaseTag implements Factory\StaticMethod
Assert::notNull($typeResolver);
Assert::notNull($descriptionFactory);
$parts = preg_split('/\s+/Su', $body, 2);
Assert::isArray($parts);
list($type, $description) = self::splitBodyIntoTypeAndTheRest($body);
$type = $typeResolver->resolve($parts[0] ?? '', $context);
$description = $descriptionFactory->create($parts[1] ?? '', $context);
$type = $typeResolver->resolve($type, $context);
$description = $descriptionFactory->create($description, $context);
return new static($type, $description);
}
@@ -71,4 +70,29 @@ final class Return_ extends BaseTag implements Factory\StaticMethod
{
return $this->type . ' ' . (string) $this->description;
}
private static function splitBodyIntoTypeAndTheRest(string $body) : array
{
$type = '';
$nestingLevel = 0;
for ($i = 0; $i < strlen($body); $i++) {
$character = $body[$i];
if (trim($character) === '' && $nestingLevel === 0) {
break;
}
$type .= $character;
if (in_array($character, ['<', '(', '[', '{'])) {
$nestingLevel++;
}
if (in_array($character, ['>', ')', ']', '}'])) {
$nestingLevel--;
}
}
$description = trim(substr($body, strlen($type)));
return [$type, $description];
}
}