PHP: ReflectionClass::getDocComment – Manual
ReflectionClass::getDocCommentはその名の通りクラスのDocコメントを取得するメソッドです。次のようにクラスのコメントを取得できます。
<?php
/**
* @property string $fuga
*/
class Hoge {
public $fuga;
public function __construct($fuga){
$this->fuga = $fuga;
}
}
$rc = new ReflectionClass('Hoge');
var_dump($rc->getDocComment());
//
// string(36) "/**
// * @property string $fuga
// */"
これによってコメントとプログラム内を結び付けられました。これを元にコメントを反映するテストを書くことができます。例えば、次です。
<?php
/**
* @property string $fuga
* @property string $foo
*/
class Hoge {
public $fuga;
public function __construct($fuga){
$this->fuga = $fuga;
}
}
// Docコメント取得
$rc = new ReflectionClass('Hoge');
$doc = $rc->getDocComment();
$lines = explode(PHP_EOL, $doc);
// プロパティ名抜き出し
$properties = [];
foreach ($lines as $line) {
if (preg_match('/@property\s+\w+\s+\$(.+)$/', $line, $matches)) {
$properties[] = trim($matches[1]);
}
}
// プロパティの存在をテスト
$hoge = new Hoge('hoge');
foreach($properties as $property){
assert(isset($hoge->$property), "property ${property} is not exist.");
}
// <br />
// <b>Warning</b>: assert(): property foo is not exist. failed in <b>[...][...]</b> on line <b>26</b><br />
これによってデータベースの変更を反映していないORMのコードを発見したりできます。もっと突き詰めるとDocコメントを元にオリジナルのアクセス制御、自動コード生成を実現できます。