Skip to content

Commit

Permalink
Copy MaxSteps from TemplateOptions (#671)
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastienros authored May 30, 2024
1 parent 4f8c5c9 commit a90842d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
13 changes: 11 additions & 2 deletions Fluid.Tests/TemplateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -832,11 +832,20 @@ public async Task ShouldLimitSteps()
{
_parser.TryParse("{% for w in (1..10000) %} FOO {% endfor %}", out var template, out var error);

var options = new TemplateOptions();
// Options are inherited from TemplateOptions
var options = new TemplateOptions
{
MaxSteps = 100
};

var context = new TemplateContext(options);
options.MaxSteps = 100;

await Assert.ThrowsAsync<InvalidOperationException>(() => template.RenderAsync(context).AsTask());

// Options are customized on TemplateContext
context.MaxSteps = 0;

await template.RenderAsync(context).AsTask();
}

[Fact]
Expand Down
11 changes: 9 additions & 2 deletions Fluid/TemplateContext.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Fluid.Values;
using System.Globalization;
using System.Runtime.CompilerServices;

namespace Fluid
{
Expand Down Expand Up @@ -52,6 +53,7 @@ public TemplateContext(TemplateOptions options)
TimeZone = options.TimeZone;
Captured = options.Captured;
Now = options.Now;
MaxSteps = options.MaxSteps;
}

/// <summary>
Expand Down Expand Up @@ -82,6 +84,11 @@ public TemplateContext(object model, bool allowModelMembers = true) : this()
/// </summary>
public TemplateOptions Options { get; protected set; }

/// <summary>
/// Gets or sets the maximum number of steps a script can execute. Leave to 0 for unlimited.
/// </summary>
public int MaxSteps { get; set; } = TemplateOptions.Default.MaxSteps;

/// <summary>
/// Gets or sets the <see cref="CultureInfo"/> instance used to render locale values like dates and numbers.
/// </summary>
Expand All @@ -100,10 +107,10 @@ public TemplateContext(object model, bool allowModelMembers = true) : this()
/// <summary>
/// Increments the number of statements the current template is processing.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void IncrementSteps()
{
var maxSteps = Options.MaxSteps;
if (maxSteps > 0 && _steps++ > maxSteps)
if (MaxSteps > 0 && _steps++ > MaxSteps)
{
ExceptionHelper.ThrowMaximumRecursionException();
}
Expand Down

0 comments on commit a90842d

Please sign in to comment.