【问题标题】:How to parse doc comments如何解析文档评论
【发布时间】:2012-07-12 18:59:48
【问题描述】:

我正在使用反射从方法中获取文档注释: http://www.php.net/manual/en/reflectionclass.getdoccomment.php,看起来像这样:

   /** 
    * Method description
    *
    * @param  array $foo    Bla bla
    * @return string        More bla bla
    */

如何将此字符串解析为我可以使用的内容? 我需要从中提取“方法描述”文本。其他的东西对我来说并不重要,因为我可以使用其他反射方法来获取参数等。

【问题讨论】:

  • 不确定这是否对您有用,但您是否查看过phpDocumenter

标签: 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 方面没有太多经验,但是,将其视为字符串,我要做的是:

    1. 按新行展开:
    2. 修剪空格和 * 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 始终采用该格式。

      【讨论】:

        猜你喜欢
        • 2016-10-13
        • 2016-02-21
        • 2012-05-31
        • 1970-01-01
        • 1970-01-01
        • 2011-08-08
        • 1970-01-01
        • 2014-08-08
        • 1970-01-01
        相关资源
        最近更新 更多