Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make global variables dynamic in t4-templates and remove method GetFo… #40

Merged
merged 1 commit into from
Nov 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 2 additions & 26 deletions src/ManiaTemplates/Lib/MtTransformer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,10 @@ private string CreateTemplatePropertiesBlock(MtComponent mtComponent)
{
var properties = new StringBuilder();

foreach (var (propertyName, propertyValue) in _engine.GlobalVariables)
foreach (var propertyName in _engine.GlobalVariables.Keys)
{
var type = propertyValue.GetType();

properties.AppendLine(_maniaTemplateLanguage
.FeatureBlock($"public {GetFormattedName(type)} ?{propertyName} {{ get; init; }}").ToString());
.FeatureBlock($"public dynamic ?{propertyName} {{ get; init; }}").ToString());
}

foreach (var property in mtComponent.Properties.Values)
Expand All @@ -186,28 +184,6 @@ private string CreateTemplatePropertiesBlock(MtComponent mtComponent)

return properties.ToString();
}

/// <summary>
/// Returns the type name. If this is a generic type, appends
/// the list of generic type arguments between angle brackets.
/// (Does not account for embedded / inner generic arguments.)
///
/// From: https://stackoverflow.com/a/66604069
/// </summary>
/// <param name="type">The type.</param>
/// <returns>System.String.</returns>
public static string GetFormattedName(Type type)
{
if(type.IsGenericType)
{
string genericArguments = type.GetGenericArguments()
.Select(x => x.Name)
.Aggregate((x1, x2) => $"{x1}, {x2}");
return $"{type.Name.Substring(0, type.Name.IndexOf("`"))}"
+ $"<{genericArguments}>";
}
return type.Name;
}

/// <summary>
/// Creates a block containing all render methods used in the template.
Expand Down
42 changes: 42 additions & 0 deletions tests/ManiaTemplates.Tests/IntegrationTests/DynamicDictionary.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Dynamic;

namespace ManiaTemplates.Tests.IntegrationTests;

/*
* From https://learn.microsoft.com/de-de/dotnet/api/system.dynamic.dynamicobject?view=net-8.0
*/
public class DynamicDictionary: DynamicObject
{
// The inner dictionary.
Dictionary<string, object> dictionary
= new Dictionary<string, object>();

// If you try to get a value of a property
// not defined in the class, this method is called.
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
// Converting the property name to lowercase
// so that property names become case-insensitive.
string name = binder.Name.ToLower();

// If the property name is found in a dictionary,
// set the result parameter to the property value and return true.
// Otherwise, return false.
return dictionary.TryGetValue(name, out result);

Check warning on line 26 in tests/ManiaTemplates.Tests/IntegrationTests/DynamicDictionary.cs

View workflow job for this annotation

GitHub Actions / build_and_test

Possible null reference assignment.

Check warning on line 26 in tests/ManiaTemplates.Tests/IntegrationTests/DynamicDictionary.cs

View workflow job for this annotation

GitHub Actions / build_and_test

Possible null reference assignment.
}

// If you try to set a value of a property that is
// not defined in the class, this method is called.
public override bool TrySetMember(

Check warning on line 31 in tests/ManiaTemplates.Tests/IntegrationTests/DynamicDictionary.cs

View workflow job for this annotation

GitHub Actions / build_and_test

Nullability of type of parameter 'value' doesn't match overridden member (possibly because of nullability attributes).

Check warning on line 31 in tests/ManiaTemplates.Tests/IntegrationTests/DynamicDictionary.cs

View workflow job for this annotation

GitHub Actions / build_and_test

Nullability of type of parameter 'value' doesn't match overridden member (possibly because of nullability attributes).
SetMemberBinder binder, object value)
{
// Converting the property name to lowercase
// so that property names become case-insensitive.
dictionary[binder.Name.ToLower()] = value;

// You can always add a value to a dictionary,
// so this method always returns true.
return true;
}
}
28 changes: 19 additions & 9 deletions tests/ManiaTemplates.Tests/IntegrationTests/ManialinkEngineTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
public class ManialinkEngineTest
{
private readonly ManiaTemplateEngine _maniaTemplateEngine = new();

[Theory]
[ClassData(typeof(TestDataProvider))]
public void Should_Convert_Templates_To_Result(string template, dynamic data, string expected)
{
_maniaTemplateEngine.AddTemplateFromString("test", template);
_maniaTemplateEngine.PreProcess("test", new[] { typeof(ManiaTemplateEngine).Assembly });

var pendingResult = _maniaTemplateEngine.RenderAsync("test", data, new[] { typeof(ManiaTemplateEngine).Assembly });

var pendingResult =
_maniaTemplateEngine.RenderAsync("test", data, new[] { typeof(ManiaTemplateEngine).Assembly });
var result = pendingResult.Result;

Assert.Equal(expected, result, ignoreLineEndingDifferences: true);
}

Expand All @@ -27,14 +28,23 @@ public void Should_Pass_Global_Variables()

_maniaTemplateEngine.AddTemplateFromString("ComponentGlobalVariable", componentWithGlobalVariable);
_maniaTemplateEngine.AddTemplateFromString("GlobalVariables", componentTemplate);


dynamic dynamicObject = new DynamicDictionary();
dynamicObject.DynamicProperty = "UnitTest";
AddGlobalVariable("dynamicObject", dynamicObject);

_maniaTemplateEngine.GlobalVariables["testVariable"] = "unittest";
_maniaTemplateEngine.GlobalVariables["complex"] = new ComplexDataType();
_maniaTemplateEngine.GlobalVariables["list"] = new List<int> { 3, 6, 9 };
var pendingResult = _maniaTemplateEngine.RenderAsync("GlobalVariables", new{}, assemblies);

var pendingResult = _maniaTemplateEngine.RenderAsync("GlobalVariables", new { }, assemblies);
var result = pendingResult.Result;

Assert.Equal(expectedOutput, result, ignoreLineEndingDifferences: true);
}
}

private void AddGlobalVariable(string name, object value)
{
_maniaTemplateEngine.GlobalVariables.AddOrUpdate(name, value, (s, o) => value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@
<label text="6" />
<label text="9" />
<label class="inner" text="UnitTest" />
<label text="UnitTest" />
</manialink>
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
<label foreach="int testList in complex.TestEnumerable" text="{{ testList }}"/>
<label foreach="int testListTwo in list" text="{{ testListTwo }}"/>
<ComponentGlobalVariable />
<label text="{{ dynamicObject.DynamicProperty }}"/>
</template>
</component>
Loading