summaryrefslogtreecommitdiff
path: root/src/SMAPI.Internal.Patching/BasePatcher.cs
blob: c1936ccc1e679d0604dd29cde875aa9915793f46 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Reflection;
using HarmonyLib;

namespace StardewModdingAPI.Internal.Patching
{
    /// <summary>Provides base implementation logic for <see cref="IPatcher"/> instances.</summary>
    internal abstract class BasePatcher : IPatcher
    {
        /*********
        ** Public methods
        *********/
        /// <inheritdoc />
        public abstract void Apply(Harmony harmony, IMonitor monitor);


        /*********
        ** Protected methods
        *********/
        /// <summary>Get a method and assert that it was found.</summary>
        /// <typeparam name="TTarget">The type containing the method.</typeparam>
        /// <param name="parameters">The method parameter types, or <c>null</c> if it's not overloaded.</param>
        protected ConstructorInfo RequireConstructor<TTarget>(params Type[] parameters)
        {
            return PatchHelper.RequireConstructor<TTarget>(parameters);
        }

        /// <summary>Get a method and assert that it was found.</summary>
        /// <typeparam name="TTarget">The type containing the method.</typeparam>
        /// <param name="name">The method name.</param>
        /// <param name="parameters">The method parameter types, or <c>null</c> if it's not overloaded.</param>
        /// <param name="generics">The method generic types, or <c>null</c> if it's not generic.</param>
        protected MethodInfo RequireMethod<TTarget>(string name, Type[]? parameters = null, Type[]? generics = null)
        {
            return PatchHelper.RequireMethod<TTarget>(name, parameters, generics);
        }

        /// <summary>Get a Harmony patch method on the current patcher instance.</summary>
        /// <param name="name">The method name.</param>
        /// <param name="priority">The patch priority to apply, usually specified using Harmony's <see cref="Priority"/> enum, or <c>null</c> to keep the default value.</param>
        protected HarmonyMethod GetHarmonyMethod(string name, int? priority = null)
        {
            HarmonyMethod method = new(
                AccessTools.Method(this.GetType(), name)
                ?? throw new InvalidOperationException($"Can't find patcher method {PatchHelper.GetMethodString(this.GetType(), name)}.")
            );

            if (priority.HasValue)
                method.priority = priority.Value;

            return method;
        }
    }
}