GenerateModelAnnotation.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. <?php
  2. namespace UCore\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Facades\DB;
  6. use UCore\ModelCore;
  7. /**
  8. * 自动生成Eloquent模型属性注释
  9. *
  10. * 通过分析数据库表结构,自动生成模型属性的PHPDoc注释,
  11. * 并提供fillable字段自动维护功能。
  12. *
  13. * 功能特性:
  14. * 1. 自动识别字段类型并生成对应property注释
  15. * 2. 特殊时间字段自动识别为Carbon类型
  16. * 3. 自动维护模型$attrlist属性包含所有字段
  17. *
  18. * 使用说明:
  19. * 1. 在模型中添加标记注释:
  20. * - 属性注释区域标记:在模型文件中添加 field start 和 field end 注释块
  21. * - fillable字段标记:在模型文件中添加 attrlist start 和 attrlist end 注释块
  22. *
  23. * @package UCore\Commands
  24. * @example php artisan ucore:generate-model-annotation
  25. */
  26. class GenerateModelAnnotation extends Command
  27. {
  28. /**
  29. * The name and signature of the console command.
  30. *
  31. * @var string
  32. */
  33. protected $signature = 'ucore:generate-model-annotation';
  34. /**
  35. * The console command description.
  36. *
  37. * @var string
  38. */
  39. protected $description = '生成模型property注释,使得IDE有模型属性提示!';
  40. private $fillable = [];
  41. /**
  42. * 主执行方法
  43. *
  44. * 扫描指定目录下的模型文件并生成注释
  45. *
  46. * @return void
  47. */
  48. public function handle()
  49. {
  50. // 扫描核心模型目录
  51. $ucoreModelsDir = app_path('../UCore/Models');
  52. if (is_dir($ucoreModelsDir)) {
  53. $this->call1($ucoreModelsDir, '\UCore\Models\\');
  54. } else {
  55. $this->warn("UCore Models 目录不存在: $ucoreModelsDir");
  56. }
  57. // 扫描模块下的Models目录
  58. $modulesPath = app_path('Module');
  59. if (is_dir($modulesPath)) {
  60. $modules = scandir($modulesPath);
  61. foreach ($modules as $module) {
  62. if ($module === '.' || $module === '..') {
  63. continue;
  64. }
  65. $modelsDir = "$modulesPath/$module/Models";
  66. if (is_dir($modelsDir)) {
  67. // 添加模块扫描日志
  68. $this->info("扫描模块目录: $modelsDir");
  69. // 修复模块命名空间格式
  70. $namespace = "App\\Module\\$module\\Models\\";
  71. // 统一目录分隔符
  72. $namespace = str_replace('/', '\\', $namespace);
  73. // 添加自动加载提示
  74. $this->warn("请确保已配置composer自动加载: \"App\\Module\\$module\\Models\\\": \"app/Module/$module/Models/\"");
  75. $this->call1($modelsDir, $namespace);
  76. }
  77. }
  78. }
  79. }
  80. // ... 保持原有call1、call2、getAnnotation方法不变 ...
  81. /**
  82. * 扫描模型目录
  83. *
  84. * @param string $dir 模型文件目录路径
  85. * @param string $ns 模型类命名空间
  86. */
  87. public function call1($dir, $ns)
  88. {
  89. $this->info("扫描目录: $dir");
  90. $list = scandir($dir);
  91. foreach ($list as $item) {
  92. if ($item === '.' || $item === '..') {
  93. continue;
  94. }
  95. $fullPath = $dir . '/' . $item;
  96. // 递归处理子目录
  97. if (is_dir($fullPath)) {
  98. $this->call1($fullPath, $ns . $item . '\\');
  99. continue;
  100. }
  101. $p = strpos($item, '.php');
  102. if ($p !== false) {
  103. $model = substr($item, 0, $p);
  104. // 修复命名空间拼接逻辑
  105. $modelClass = rtrim($ns, '\\') . '\\' . $model;
  106. // 修复文件路径拼接
  107. $file = $fullPath;
  108. $this->call2($model, $modelClass, $file);
  109. }
  110. }
  111. }
  112. /**
  113. * 处理单个模型文件
  114. *
  115. * @param string $model 模型类名
  116. * @param string $modelClass 完整模型类名
  117. * @param string $file 模型文件路径
  118. */
  119. public function call2($model,$modelClass,$file)
  120. {
  121. if(class_exists($modelClass)){
  122. // 检查类是否是抽象类
  123. $reflectionClass = new \ReflectionClass($modelClass);
  124. if ($reflectionClass->isAbstract()) {
  125. $this->output->warning(" model $modelClass 是抽象类,跳过");
  126. return;
  127. }
  128. // 检查类是否是模型类
  129. if (!$reflectionClass->isSubclassOf(\Illuminate\Database\Eloquent\Model::class)) {
  130. $this->output->warning(" model $modelClass 不是模型类,跳过");
  131. return;
  132. }
  133. // 检查构造函数是否需要参数
  134. $constructor = $reflectionClass->getConstructor();
  135. if ($constructor && $constructor->getNumberOfRequiredParameters() > 0) {
  136. $this->output->warning(" model $modelClass 需要构造函数参数,跳过");
  137. return;
  138. }
  139. /**
  140. * @var ModelCore $model
  141. */
  142. try {
  143. $model = new $modelClass();
  144. } catch (\Throwable $e) {
  145. $this->output->error(" model $modelClass 实例化失败: " . $e->getMessage());
  146. return;
  147. }
  148. if($model instanceof Model){
  149. $co = $model->getConnection();
  150. $tTablePrefix = $co->getTablePrefix();
  151. $table =$tTablePrefix.$model->getTable();
  152. $this->info("table $table ");
  153. $annotation = $this->getAnnotation($table,$co);
  154. $pattern = '/field start[\s\S]+field end/';
  155. $replacement = "field start ".$annotation." * field end";
  156. $string = file_get_contents($file);
  157. $result = preg_replace($pattern, $replacement, $string);
  158. // 过滤系统默认字段
  159. $filteredFillable = array_filter($this->fillable, function($field) {
  160. return !in_array($field, ['created_at', 'updated_at', 'deleted_at']);
  161. });
  162. // 格式化数组输出
  163. $fillableContent = " protected \$fillable = [\n";
  164. foreach ($filteredFillable as $field) {
  165. $fillableContent .= " '{$field}',\n";
  166. }
  167. $fillableContent .= " ];";
  168. $pattern2 = '/attrlist start[\s\S]+attrlist end/';
  169. $replacement2 = "attrlist start \n{$fillableContent}\n // attrlist end";
  170. $result = preg_replace($pattern2, $replacement2, $result);
  171. if($result != $string){
  172. $this->output->info(" model $modelClass file :$file annotation 成功 ");
  173. file_put_contents($file,$result);
  174. }else{
  175. $this->output->warning(" model $modelClass file :$file table $table - 没有标识符 ");
  176. }
  177. }else{
  178. $this->output->warning(" model $modelClass 不是继承 ModelBase");
  179. }
  180. }else{
  181. $this->output->warning(" model $model 不存在");
  182. }
  183. }
  184. /**
  185. * 生成属性注释字符串
  186. *
  187. * @param string $tableName 数据库表名
  188. * @param \Illuminate\Database\Connection $con 数据库连接
  189. * @return string 生成的注释字符串
  190. * @throws \Exception 当数据库查询失败时
  191. */
  192. public function getAnnotation($tableName,\Illuminate\Database\Connection $con)
  193. {
  194. $db = $con->getDatabaseName();
  195. $fillable = [];
  196. $sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
  197. WHERE table_name = '{$tableName}' AND TABLE_SCHEMA = '{$db}'
  198. ORDER BY ORDINAL_POSITION ASC";
  199. $columns = $con->select($sql);
  200. $annotation = "";
  201. foreach ($columns as $column) {
  202. $type = $this->getColumnType($column->DATA_TYPE);
  203. $columnName = $column->COLUMN_NAME;
  204. $fillable[] = $columnName;
  205. $type = $this->handleSpecialColumns($columnName, $type);
  206. $annotation .= sprintf("\n * @property %s \$%s %s",
  207. $type,
  208. $columnName,
  209. $column->COLUMN_COMMENT);
  210. }
  211. $this->fillable = $fillable;
  212. return $annotation."\n";
  213. }
  214. private function getColumnType($dataType)
  215. {
  216. return match($dataType) {
  217. 'int', 'tinyint', 'smallint', 'mediumint', 'bigint' => 'int',
  218. 'float', 'double', 'decimal' => 'float',
  219. 'json' => 'object|array',
  220. default => 'string'
  221. };
  222. }
  223. private function handleSpecialColumns($columnName, $type)
  224. {
  225. if (in_array($columnName, ['created_at', 'updated_at', 'deleted_at'])) {
  226. return '\\Carbon\\Carbon';
  227. }
  228. return $type;
  229. }
  230. }