diff --git a/src/ReC.Application/Common/Behaviors/InvokeAction/PlaceholderExtensions.cs b/src/ReC.Application/Common/Behaviors/InvokeAction/PlaceholderExtensions.cs index f53745c..427ee34 100644 --- a/src/ReC.Application/Common/Behaviors/InvokeAction/PlaceholderExtensions.cs +++ b/src/ReC.Application/Common/Behaviors/InvokeAction/PlaceholderExtensions.cs @@ -1,10 +1,51 @@ using System.ComponentModel.DataAnnotations.Schema; using System.Reflection; +using System.Text.RegularExpressions; +using ReC.Application.Common.Exceptions; namespace ReC.Application.Common.Behaviors.InvokeAction; -public static class PlaceholderExtensions +public static partial class PlaceholderExtensions { + [GeneratedRegex(@"\{#[^#]+#[^}]+\}")] + private static partial Regex PlaceholderRegex(); + + /// + /// Replaces placeholders in the format {#ANY_STRING#COLUMN_NAME} with the corresponding + /// property value resolved via from the provided objects. + /// Values are converted to SQL-compatible string representations. + /// + /// + /// Thrown when a placeholder's column name cannot be resolved from any of the provided objects. + /// + public static string ReplacePlaceholders(this string str, params object[] objects) + { + return PlaceholderRegex().Replace(str, match => + { + var placeholder = match.Value; + var inner = placeholder[2..^1]; // remove {# and } + var lastHash = inner.LastIndexOf('#'); + var columnName = inner[(lastHash + 1)..]; + + foreach (var obj in objects) + { + var value = obj.GetValueByColumnName(columnName); + if (value is not null) + return ToSqlLiteral(value); + } + + throw new PlaceholderResolutionException(placeholder, columnName, str); + }); + } + + private static string ToSqlLiteral(object value) => value switch + { + bool b => b ? "TRUE" : "FALSE", + DateTime dt => dt.ToString("yyyy-MM-dd HH:mm:ss"), + DateTimeOffset dto => dto.ToString("yyyy-MM-dd HH:mm:ss zzz"), + _ => value.ToString() ?? string.Empty + }; + /// /// Gets the value of a property by its column name defined in . /// Returns null if no property with the given column name exists.