Skip to content

Commit

Permalink
Update NameFormatter.cs
Browse files Browse the repository at this point in the history
  • Loading branch information
pwelter34 committed Aug 21, 2024
1 parent 39646c3 commit 094b045
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/LoreSoft.Extensions/Text/NameFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,36 +39,47 @@ public static string FormatName(this string format, object source)
var ch = e.Current;
if (ch == '{')
{
// start expression block, continue till closing char
while (true)
{
// end of format string without closing expression
if (!e.MoveNext())
throw new FormatException();

ch = e.Current;
if (ch == '}')
{
// close expression block, evaluate expression and add to result
string value = Evaluate(source, expression.ToString());
result.Append(value);

// reset expression buffer
expression.Length = 0;
break;
}
if (ch == '{')
{
// double expression start, add to result
result.Append(ch);
break;
}

// add to expression buffer
expression.Append(ch);
}
}
else if (ch == '}')
{
// close expression char without having started one
if (!e.MoveNext() || e.Current != '}')
throw new FormatException();

// double expression close, add to result
result.Append('}');
}
else
{
// normal char, add to result
result.Append(ch);
}
}
Expand All @@ -83,13 +94,15 @@ private static string Evaluate(object source, string expression)

string format = null;

// support format string {0:d}
int colonIndex = expression.IndexOf(':');
if (colonIndex > 0)
{
format = expression[(colonIndex + 1)..];
expression = expression[..colonIndex];
}

// better way to support more dictionary generics?
if (source is IDictionary<string, string> stringDictionary)
{
stringDictionary.TryGetValue(expression, out var value);
Expand Down Expand Up @@ -119,6 +132,7 @@ private static object GetValue(object target, string name)

PropertyInfo property = null;

// optimization if no nested property
if (!name.Contains('.'))
{
property = currentType.GetRuntimeProperty(name);
Expand All @@ -130,13 +144,15 @@ private static object GetValue(object target, string name)
{
if (property != null)
{
// pending property, get value and type
currentTarget = property.GetValue(currentTarget);
currentType = property.PropertyType;
}

property = currentType.GetRuntimeProperty(part);
}

// return last property
return property?.GetValue(currentTarget);
}

Expand Down

0 comments on commit 094b045

Please sign in to comment.