はじめに
PhpDoc皆さん書いてますか?
補完を最大限効かせるためにできれば全部書いていきたいですが、抜けているかどうかのチェックを目視で確認するのって面倒ですよね。
面倒なことは自動化しちゃいましょう!
仕組み
PHPにはクラス情報を取得するReflectionClassという関数があります。
そして、この関数を使うとなんと!PhpDocの情報も取得できたりします。
つまり、書いてなければnullが返ってきます。
※補足すると各メソッドの行番号やプロパティの内容、publicかどうかなども取得できます。
サンプルコード
/**
* Class PhpDocCheckCommand
*/
class PhpDocCheckCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'php_doc_check {target_directory_path}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'phpdocの存在をチェックする';
/**
* phpdocの存在をチェックする
*/
public function handle()
{
$target_directory_path = app_path($this->argument('target_directory_path'));
$check_php_doc = new CheckPhpDoc();
$check_php_doc->run($target_directory_path);
}
}
/**
* Class CheckPhpDoc
*/
class CheckPhpDoc
{
/**
* 指定ファイル内のPhpDocが正しく書かれているかどうかを検証する
*
* @param string $target_directory_path 対象のディレクトリのパス
*/
public function run(string $target_directory_path)
{
foreach (ClassMapGenerator::createMap($target_directory_path) as $model => $class_file_path) {
$this->verifyPhpDoc($model);
}
}
/**
* クラスのPhpDocの検証
*
* @param $model
*/
private function verifyPhpDoc($model)
{
$reflection = new ReflectionClass($model);
// クラスのPhpDocの検証
if (empty($reflection->getDocComment())) {
throw new LogicException(sprintf('%sクラスのPhoDocが未定義です。必ず入力して下さい', $reflection->getName()));
}
// クラス内のプロパティのPhpDocの検証
foreach ($reflection->getProperties() as $property) {
if (empty($property->getDocComment())) {
throw new LogicException(sprintf('%sのプロパティである%sのPhoDocが未定義です。必ず入力して下さい', $reflection->getName(), $property->getName()));
}
}
// クラス内のメソッドのPhpDocの検証
foreach ($reflection->getMethods() as $method) {
if (empty($method->getDocComment())) {
throw new LogicException(sprintf('%sのメソッドである%sのPhoDocが未定義です。必ず入力して下さい', $reflection->getName(), $method->getName()));
}
}
}