美文网首页
tp6自动更新模型

tp6自动更新模型

作者: 耍帅oldboy | 来源:发表于2023-03-31 02:26 被阅读0次

更新命令
php think amp model/

<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\facade\App;
use think\Model;
use think\facade\Db;


class amp 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)
    {
        // 指令输出
        $output->writeln('amp');
        $modelPath = $input->getArgument('model');
        $path = App::getAppPath() . $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 {
            throw new Exception("$path 文件不存在");
        }

        $output->writeln("success");
    }

    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 {
                        throw new Exception("$class 不是模型类");
                    }
                } else {
                    throw new Exception("$class 不存在");
                }

            } else {
                throw new Exception("未能找到" . basename($filePath) . "类的名字");
            }

        } else {
            throw new Exception("未能找到" . basename($filePath) . "类的命名空间");
        }

    }

    /**
     * 扫码数据表的属性
     * @param Model $model
     * @param $comments
     * @return string
     */
    protected function parseTableAttr(Model $model, &$comments)
    {
        $schema = Db::getConfig('connections.mysql.database');
        $data = Db::query("SELECT COLUMN_NAME, DATA_TYPE , COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name='{$model->getTable()}' and table_schema='{$schema}'");

        foreach ($data as $val){
            $comments[] = " * @property $" . $val['COLUMN_NAME'] . self::$tabs . $val['DATA_TYPE'].self::$tabs.$val['COLUMN_COMMENT'];
        }
    }

    /**
     * 获取模型文件的方法
     * @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 = $this->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 = $this->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 '';
    }

    /**
     * 字符串命名风格转换
     * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
     * @access public
     * @param  string  $name 字符串
     * @param  integer $type 转换类型
     * @param  bool    $ucfirst 首字母是否大写(驼峰规则)
     * @return string
     */
    protected function parseName($name, $type = 0, $ucfirst = true)
    {
        if ($type) {
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $name);
            return $ucfirst ? ucfirst($name) : lcfirst($name);
        }
        return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
    }
}

相关文章

网友评论

      本文标题:tp6自动更新模型

      本文链接:https://www.haomeiwen.com/subject/qmthddtx.html