基于thinkphp的模型文件自動注釋生成器

thinkphp 一個模型對應一個數(shù)據(jù)表,所以數(shù)據(jù)表里面字段也是模型的一些屬性,但是因為php是動態(tài)語言,模型里面的屬性并不能直觀的看到,出了數(shù)據(jù)表里面的字段以外的屬性,模型其實還包含了通過getXXXAttr方法定義的屬性,還有關聯(lián)關系定義的屬性比如hasOne,hasMany等等。雖然thinkphp支持了通過訪問數(shù)組的形式訪問模型的屬性,但是還是不直觀,另一個是不知道模型屬性的字段含義,如果手動維護容易遺漏和出錯,所以我基于thinkphp5.1開發(fā)了模型屬性自動生成器。

倉庫地址:https://github.com/xiaobai1993/model_property_helper,支持composer 安裝。

功能介紹

  • 基于thinkphp的command命令類,提供基本的交互。
  • 自動更新模型的屬性,同時生成注釋。包括數(shù)據(jù)表字段、獲取器定義,關聯(lián)關系定義。
  • 支持在同一個目錄下的所有的模型統(tǒng)一更新,也支持單個模型文件更新。
  • 根據(jù)數(shù)據(jù)表創(chuàng)建的語句中字段的注釋或者php文件中的注釋,自動為屬性增加注釋信息。

源碼如下

<?php
/**
 * Created by PhpStorm.
 * User: guodong
 * Date: 2020/4/2
 * Time: 下午2:35
 */

namespace app\common\command\code;


use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Loader;
use think\Model;

class ModelProperty extends Command
{
    protected static $tabs = "   ";

    protected function configure()
    {
        $this->setName('amp')
            ->addArgument('model', Argument::OPTIONAL, "模型的名字")
            ->addOption('override', null, Option::VALUE_OPTIONAL, '是否強制覆蓋')
            ->setDescription('模型自動增加屬性注釋');
    }

    protected function execute(Input $input, Output $output)
    {
        $modelPath = $input->getArgument('model');
        $path = APP_PATH . $modelPath;
        if (is_dir($path)) {
            foreach (scandir($path) as $value) {
                if ($value == '.' || $value == '..') {
                    continue;
                }
                $filePath = $path . "/" . $value;
                if (is_file($filePath)) {
                    try {
                        $this->parseSingleFile($filePath);
                    } catch (\Exception $exception) {
                        echo $exception->getMessage();
                    }
                } else {
                    continue;//目錄嵌套暫時不處理
                }
            }
        } elseif (is_file($path)) {
            $this->parseSingleFile($path);
        } else {
            exception("$path 文件不存在");
        }
    }


    public function parseSingleFile($filePath)
    {
        $fileContent = file_get_contents($filePath);
        if (preg_match('/namespace (.*?);/', $fileContent, $spaceMatch)) {
            $spaceName = $spaceMatch[1];
            if (preg_match('/class (.*?) extends .*?Model/', $fileContent, $classMatch)) {
                $className = $classMatch[1];
                $class = $spaceName . "\\" . $className;
                if (class_exists($class)) {
                    $instance = new $class();
                    if ($instance instanceof Model) {
                        $comments = [];
                        $this->parseTableAttr($instance, $comments);
                        $this->parseClass($instance, $comments);
                        $classComments = "\n\n/**\n" . implode("\n", $comments) . "\n*/\n\n";
                        $result = preg_replace('/^([\s\S]*;)([\s\S]*?)(class.*?extends[\s\S]*)$/', "$1$classComments$3", $fileContent);
                        file_put_contents($filePath, $result);
                    } else {
                        exception("$class 不是模型類");
                    }
                } else {
                    exception("$class 不存在");
                }
            } else {
                exception("未能找到" . basename($filePath) . "類的名字");
            }

        } else {
            exception("未能找到" . basename($filePath) . "類的命名空間");
        }
    }

    /**
     * 掃碼數(shù)據(jù)表的屬性
     * @param Model $model
     * @param $comments
     * @return string
     */
    protected function parseTableAttr(Model $model, &$comments)
    {
        $tableSql = $model->query("show create table " . $model->getTable())[0]['Create Table'];
        preg_match_all("#`(.*?)`(.*?) COMMENT\s*'(.*?)',#", $tableSql, $matches);
        $fields = $matches[1];
        $cts = $matches[3];
        if (preg_match('/COMMENT=\'(.*?)\'$/', $tableSql, $m2)) {
            $comments[] = " * " . $m2[1];
        }
        for ($i = 0; $i < count($matches[0]); $i++) {
            $comments[] = " * @property $" . $fields[$i] . self::$tabs . $cts[$i];
        }
    }

    /**
     * 獲取模型文件的方法
     * @param $model
     * @param $comments
     */
    protected function parseClass(Model $model, &$comments)
    {
        $classReflect = new \ReflectionClass($model);
        $tableFields = $model->getTableFields();
        $filePath = $classReflect->getFileName();
        if ($filePath) {
            $content = file_get_contents($filePath);
        } else {
            $content = "";
        }
        $methods = $classReflect->getMethods(\ReflectionMethod::IS_PUBLIC);
        foreach ($methods as $method) {
            if ($method->isAbstract() || $method->isStatic()) {
                continue;
            }
            $methodName = $method->getName();
            //只查詢本類文件存在的
            if ($content && strpos($content, "function " . $methodName)) {
                if (preg_match('/get(.*?)Attr/', $methodName, $match)) { //屬性
                    $propertyName = Loader::parseName($match[1], 0, false);
                    if (in_array($propertyName, $tableFields)) {
                        continue;
                    }
                    $comments[] = " * @property $" . $propertyName . self::$tabs . $this->getDocTitle($method->getDocComment());
                } else {
                    $startLine = $method->getStartLine();
                    $endLine = $method->getEndLine();
                    $methodContent = $this->readFile($filePath, $startLine, $endLine);
                    if (preg_match('/return.*?->(.*?)\([,]?(.*?)::class,/', $methodContent, $match)) {
                        $relation = $match[1];
                        $relationModel = $match[2];
                        $propertyName = Loader::parseName($methodName, 0, false);
                        if ($relation == 'hasMany' || $relation == 'belongsToMany') {
                            $comments[] = " * @property ". $relationModel . "[]" . " $" . $propertyName . self::$tabs . $this->getDocTitle($method->getDocComment());
                        } else {
                            $comments[] = " * @property " .$relationModel . " $" . $propertyName . self::$tabs . $this->getDocTitle($method->getDocComment());
                        }
                    }
                }
            } else {
                continue;
            }
        }
    }

    /**
     * 讀文件
     * @param $file_name
     * @param $start
     * @param $end
     * @return string
     */
    protected function readFile($file_name, $start, $end)
    {
        $limit = $end - $start;
        $f = new \SplFileObject($file_name, 'r');
        $f->seek($start);
        $ret = "";
        for ($i = 0; $i < $limit; $i++) {
            $ret .= $f->current();
            $f->next();
        }
        return $ret;
    }

    /**
     * 獲取類或者方法注釋的標題,第一行
     * @param $docComment
     * @return string
     */
    protected function getDocTitle($docComment)
    {
        if ($docComment !== false) {
            $docCommentArr = explode("\n", $docComment);
            $comment = trim($docCommentArr[1]);
            return trim(substr($comment, strpos($comment, '*') + 1));
        }
        return '';
    }

}

案例測試

# 整個目錄的模型都更新了
php think amp dbase/model/ 

隨便拿幾個看看

image.png
image.png

可以發(fā)現(xiàn)生成了較為完善的注釋信息,對于關聯(lián)信息也根據(jù)關聯(lián)關系指定是對象還是對象數(shù)組。

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 作為一名PHP后端開發(fā)工程師,提供給前端接口是必須的,但是作為程序員我們最痛恨自己寫文檔,最恨別人不寫文檔。對于開...
    鴻雁長飛光不度閱讀 2,004評論 4 2
  • 1、PHP語言的一大優(yōu)勢是跨平臺,什么是跨平臺?一、PHP基礎: PHP的運行環(huán)境最優(yōu)搭配為Apache+MySQ...
    __書山有路__閱讀 1,612評論 0 15
  • 理工寢室商店-微信小程序 疑問小結 當時在XAMMP下mysql目錄下的bin下 php -v 不起作用.到ph...
    這個超人不會飛阿閱讀 1,823評論 1 1
  • Eloquent: 關聯(lián)模型 簡介 數(shù)據(jù)庫中的表經(jīng)常性的關聯(lián)其它的表。比如,一個博客文章可以有很多的評論,或者一個...
    Dearmadman閱讀 17,544評論 6 16
  • .數(shù)據(jù)庫 數(shù)據(jù)庫的發(fā)展: 文件系統(tǒng)(使用磁盤文件來存儲數(shù)據(jù))=>第一代數(shù)據(jù)庫(出現(xiàn)了網(wǎng)狀模型,層次模型的數(shù)據(jù)庫)=...
    小Q逛逛閱讀 1,076評論 0 2

友情鏈接更多精彩內(nèi)容