using Microsoft.AspNetCore.Hosting;
using MiaoYu.Core.CodeGenerator.Abstractions;
namespace MiaoYu.Core.CodeGenerator.Core;
///
/// 路径解析器
///
[Component]
public class PathResolver : IScopedDependency
{
private readonly IWebHostEnvironment _environment;
public PathResolver(IWebHostEnvironment environment)
{
_environment = environment;
}
///
/// 解析路径模板
///
/// 路径模板(支持占位符)
/// 数据源配置
/// 表名
/// 解析后的完整路径
public string ResolvePath(string template, DataSourceConfig config, string tableName)
{
if (string.IsNullOrWhiteSpace(template))
return string.Empty;
var rootPath = _environment.ContentRootPath
.Replace("\\" + _environment.ApplicationName, "");
var entityName = GetEntityName(tableName, config);
var entityNamePlural = config.UsesPluralPath ? entityName + "s" : entityName;
return template
.Replace("{RootPath}", rootPath)
.Replace("{AppPath}", _environment.ContentRootPath)
.Replace("{Namespace}", config.EntityNamespace)
.Replace("{EntityName}", entityName)
.Replace("{EntityNamePlural}", entityNamePlural)
.Replace("{TableName}", tableName);
}
///
/// 根据命名策略和配置获取实体名
///
/// 表名
/// 数据源配置
/// 实体名
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;
}
///
/// 将下划线命名转换为 PascalCase
///
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();
}
}