98 lines
3.2 KiB
C#
98 lines
3.2 KiB
C#
using Microsoft.AspNetCore.Hosting;
|
|
using MiaoYu.Core.CodeGenerator.Abstractions;
|
|
|
|
namespace MiaoYu.Core.CodeGenerator.Core;
|
|
|
|
/// <summary>
|
|
/// 路径解析器
|
|
/// </summary>
|
|
[Component]
|
|
public class PathResolver : IScopedDependency
|
|
{
|
|
private readonly IWebHostEnvironment _environment;
|
|
|
|
public PathResolver(IWebHostEnvironment environment)
|
|
{
|
|
_environment = environment;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 解析路径模板
|
|
/// </summary>
|
|
/// <param name="template">路径模板(支持占位符)</param>
|
|
/// <param name="config">数据源配置</param>
|
|
/// <param name="tableName">表名</param>
|
|
/// <returns>解析后的完整路径</returns>
|
|
public string ResolvePath(string template, DataSourceConfig config, string tableName)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(template))
|
|
return string.Empty;
|
|
|
|
var rootPath = _environment.ContentRootPath
|
|
.Replace("\\" + _environment.ApplicationName, "");
|
|
var webPath = Path.GetDirectoryName(Path.GetDirectoryName(_environment.ContentRootPath))
|
|
.Replace("\\" + _environment.ApplicationName, "");
|
|
var entityName = GetEntityName(tableName, config);
|
|
var entityNamePlural = config.UsesPluralPath ? entityName + "s" : entityName;
|
|
var tableNameLower = string.IsNullOrWhiteSpace(tableName) ? string.Empty : tableName.ToLower();
|
|
|
|
return template
|
|
.Replace("{RootPath}", rootPath)
|
|
.Replace("{WebPath}", webPath)
|
|
.Replace("{AppPath}", _environment.ContentRootPath)
|
|
.Replace("{Namespace}", config.EntityNamespace)
|
|
.Replace("{EntityName}", entityName)
|
|
.Replace("{EntityNamePlural}", entityNamePlural)
|
|
.Replace("{TableName}", tableName)
|
|
.Replace("{TableNameLower}", tableNameLower);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据命名策略和配置获取实体名
|
|
/// </summary>
|
|
/// <param name="tableName">表名</param>
|
|
/// <param name="config">数据源配置</param>
|
|
/// <returns>实体名</returns>
|
|
public string GetEntityName(string tableName, DataSourceConfig config)
|
|
{
|
|
var baseName = config.NamingStrategy == EntityNamingStrategy.ToPascalCase
|
|
? ConvertToPascalCase(tableName)
|
|
: tableName;
|
|
|
|
// 应用前缀(如果启用)
|
|
if (config.EnableEntityPrefix && !string.IsNullOrWhiteSpace(config.EntityPrefix))
|
|
{
|
|
return config.EntityPrefix + baseName;
|
|
}
|
|
|
|
return baseName;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将下划线命名转换为 PascalCase
|
|
/// </summary>
|
|
private static string ConvertToPascalCase(string input)
|
|
{
|
|
if (string.IsNullOrEmpty(input))
|
|
return input;
|
|
|
|
var words = input.Split(new[] { '_', '-' }, StringSplitOptions.RemoveEmptyEntries);
|
|
var result = new System.Text.StringBuilder();
|
|
|
|
foreach (var word in words)
|
|
{
|
|
if (word.Length > 0)
|
|
{
|
|
result.Append(char.ToUpper(word[0]));
|
|
if (word.Length > 1)
|
|
{
|
|
result.Append(word.Substring(1).ToLower());
|
|
}
|
|
}
|
|
}
|
|
|
|
return result.ToString();
|
|
}
|
|
}
|
|
|