【问题标题】:How to parse doc comments如何解析文档评论
【发布时间】:2012-07-12 18:59:48
【问题描述】:
【问题讨论】:
标签:
php
string
reflection
comments
【解决方案1】:
public function parseAnnotations($doc){
preg_match_all('/@([a-z]+?)\s+(.*?)\n/i', $doc, $annotations);
if(!isset($annotations[1]) OR count($annotations[1]) == 0){
return [];
}
return array_combine(array_map("trim",$annotations[1]), array_map("trim",$annotations[2]));
}
...
$reflection = new ReflectionObject($class);
foreach($reflection->getProperties() as $property){
print_r($this->parseAnnotations($property->getDocComment()));
}
例子
/**
* @param $action
* @required FALSE
*/
private $action;
结果
Array
(
[param] => $action
[required] => FALSE
)
【解决方案2】:
我在解析 cmets 方面没有太多经验,但是,将其视为字符串,我要做的是:
- 按新行展开:
- 修剪空格和 * out
类似这样的:
<?php
$string = " /**
* Method description
*
* @param array $foo Bla bla
* @return string More bla bla
*/";
$parts = explode("\n",$string);
$comment = trim($parts[1]," *");
echo $comment; // will echo "Method description"
但是,可能并不理想,因为描述可能不止一行。
【解决方案3】:
trim(str_replace(array('/', '*'), '', substr($rc->getDocComment(), 0, strpos($rc->getDocComment(), '@'))));
假设 cmets 始终采用该格式。