refactor(DbToSchemeService): 重构字段注解生成逻辑以提高可读性

This commit is contained in:
augushong
2026-01-09 21:28:54 +08:00
parent 80fc381090
commit 0522e2f9c3

View File

@@ -150,22 +150,69 @@ class DbToSchemeService
$componentAttr = "\n #[Component(type: '$compType', options: $optionsCode)]";
}
// 构建 Field 注解
$defaultStr = is_null($default) ? 'null' : (is_string($default) ? "'$default'" : $default);
$nullable = $notNull ? 'false' : 'true';
$unsigned = str_contains($type, 'unsigned') ? 'true' : 'false';
$primaryStr = $primary ? 'true' : 'false';
$autoincStr = $autoinc ? 'true' : 'false';
// 如果是整型且未指定长度默认11 (兼容旧习俗)
if (str_contains($dbType, 'int') && !$length) {
$length = 11;
}
$lengthStr = is_null($length) ? 'null' : $length;
// 构建 Field 注解参数
$fieldParams = [];
// type (default: varchar)
if ($dbType !== 'varchar') {
$fieldParams[] = "type: '$dbType'";
}
// length (default: null)
if ($length !== null) {
$fieldParams[] = "length: $length";
}
// precision (default: 0)
if ($precision !== 0) {
$fieldParams[] = "precision: $precision";
}
// scale (default: 0)
if ($scale !== 0) {
$fieldParams[] = "scale: $scale";
}
// nullable (default: true)
if ($notNull) {
$fieldParams[] = "nullable: false";
}
// default (default: null)
if (!is_null($default)) {
$defaultVal = is_string($default) ? "'$default'" : $default;
$fieldParams[] = "default: $defaultVal";
}
// comment (default: '')
if ($cleanComment !== '') {
$fieldParams[] = "comment: '$cleanComment'";
}
// unsigned (default: false)
if (str_contains($type, 'unsigned')) {
$fieldParams[] = "unsigned: true";
}
// autoIncrement (default: false)
if ($autoinc) {
$fieldParams[] = "autoIncrement: true";
}
// primary (default: false)
if ($primary) {
$fieldParams[] = "primary: true";
}
$fieldAttrStr = implode(', ', $fieldParams);
$fieldsCode[] = <<<PHP
#[Field(type: '$dbType', length: $lengthStr, precision: $precision, scale: $scale, nullable: $nullable, default: $defaultStr, comment: '$cleanComment', unsigned: $unsigned, autoIncrement: $autoincStr, primary: $primaryStr)]$componentAttr
#[Field($fieldAttrStr)]$componentAttr
public \$$fieldName;
PHP;
}