Skip to content

Instantly share code, notes, and snippets.

@iDevelopThings
Created January 25, 2023 07:31
Show Gist options
  • Save iDevelopThings/b5c0257004aab1340005dce964cb0568 to your computer and use it in GitHub Desktop.
Save iDevelopThings/b5c0257004aab1340005dce964cb0568 to your computer and use it in GitHub Desktop.
Get php doc block annotations data(could be used alongside reflection to get return types etc)
<?php
class SomethingElse
{
}
class Something
{
/**
* @return SomethingElse
*/
public function somethingElse()
{
return new SomethingElse();
}
}
$class = new ReflectionClass(Something::class);
$method = $class->getMethod('somethingElse');
$result = preg_match_all(
'~\@([^\s@\(]+)[\t ]*(?:\(?([^\n@]+)\)?)?~i',
$method->getDocComment(),
$methodAnnotations,
PREG_PATTERN_ORDER
);
class AnnotationData
{
public function __construct(
/**
* @var string $value | The value in the annotation, for ``@return string``, this would be "string"
*/
public string $value,
/**
* @var string $key | "var", "return" etc
*/
public string $key,
) {
}
}
$annotations = [];
foreach ($methodAnnotations[0] as $key => $annotation) {
$annotations[] = new AnnotationData(
$methodAnnotations[1][$key],
$methodAnnotations[2][$key]
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment