Skip to content

Commit

Permalink
✨ Support static methods for commands (fix #2)
Browse files Browse the repository at this point in the history
  • Loading branch information
decaprime committed Aug 26, 2022
1 parent 497a355 commit 1ce767e
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
8 changes: 6 additions & 2 deletions VCF.Core/CommandRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,12 @@ static void HandleAfterExecute(ICommandContext ctx, ChatCommand command)
}
}

// construct command class with context if declared
var instance = command.Constructor == null ? Activator.CreateInstance(command.Method.DeclaringType) : command.Constructor.Invoke(new[] { ctx });
object instance = null;
// construct command's type with context if declared only in a non-static class and on a non-static method
if (!command.Method.IsStatic && !(command.Method.DeclaringType.IsAbstract && command.Method.DeclaringType.IsSealed))
{
instance = command.Constructor == null ? Activator.CreateInstance(command.Method.DeclaringType) : command.Constructor.Invoke(new[] { ctx });
}

if (!HandleCanExecute(ctx, command)) return null; // todo: need better return type
HandleBeforeExecute(ctx, command);
Expand Down
46 changes: 46 additions & 0 deletions VCF.Tests/StaticCommandsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using FakeItEasy;
using NUnit.Framework;
using VampireCommandFramework;

namespace VCF.Tests;

public class StaticCommandsTests
{
[SetUp]
public void Setup()
{
Log.Instance = new BepInEx.Logging.ManualLogSource("Test");
CommandRegistry.Reset();
}

[Test]
public void Static_Class_Static_Method_Command()
{
CommandRegistry.RegisterCommandType(typeof(StaticClassTestCommands));
Assert.IsNotNull(CommandRegistry.Handle(A.Fake<ICommandContext>(), ".test"));
}

[Test]
public void Regular_Class_Static_Method_Command()
{
CommandRegistry.RegisterCommandType(typeof(RegularClassTestCommands));
Assert.IsNotNull(CommandRegistry.Handle(A.Fake<ICommandContext>(), ".test"));
}

public static class StaticClassTestCommands
{
[ChatCommand("test")]
public static void Test(ICommandContext ctx) { }
}

public class RegularClassTestCommands
{
public RegularClassTestCommands(ICommandContext ctx)
{
Assert.Fail("Should not run this.");
}

[ChatCommand("test")]
public static void Test(ICommandContext ctx) { }
}
}

0 comments on commit 1ce767e

Please sign in to comment.