< Summary

Information
Class: Chronicler.Serialization.StateJsonConverterFactory
Assembly: Chronicler
File(s): /home/runner/work/Chronicler/Chronicler/src/Chronicler/Serialization/Json/StateJsonConverterFactory.cs
Line coverage
100%
Covered lines: 32
Uncovered lines: 0
Coverable lines: 32
Total lines: 101
Line coverage: 100%
Branch coverage
100%
Covered branches: 22
Total branches: 22
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
CanConvert(...)100%66100%
CreateConverter(...)100%22100%
HasStateBackedContract(...)100%44100%
GetSingleStateType(...)100%88100%
IsStateBackedInterface(...)100%22100%
CreateFactory(...)100%11100%

File(s)

/home/runner/work/Chronicler/Chronicler/src/Chronicler/Serialization/Json/StateJsonConverterFactory.cs

#LineLine coverage
 1//=======================================================================
 2// StateJsonConverterFactory.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2024-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using System;
 9using System.Linq.Expressions;
 10using System.Reflection;
 11using System.Text.Json;
 12using System.Text.Json.Serialization;
 13
 14namespace Chronicler.Serialization;
 15
 16/// <summary>
 17/// Creates JSON converters for types that explicitly implement <see cref="IStateBacked{TState}"/>.
 18/// </summary>
 19public sealed class StateJsonConverterFactory : JsonConverterFactory
 20{
 21    /// <summary>Checks whether the type is a candidate for state-backed conversion.</summary>
 22    /// <param name="typeToConvert">The type to inspect. Null is ineligible.</param>
 23    /// <returns>True for a concrete class that implements a state-backed interface. Constructor and contract validation
 24    public override bool CanConvert(Type typeToConvert)
 25    {
 1926        return typeToConvert != null
 1927            && typeToConvert.IsClass
 1928            && !typeToConvert.IsAbstract
 1929            && HasStateBackedContract(typeToConvert);
 30    }
 31
 32    /// <summary>Builds a state converter that invokes the record's state constructor.</summary>
 33    /// <param name="typeToConvert">A concrete class with exactly one state-backed interface and a public constructor ac
 34    /// <param name="options">The calling serializer's configuration. Constructor selection depends on the declared reco
 35    /// <returns>A converter whose constructor delegate is bound to the record's public state constructor.</returns>
 36    /// <remarks>Discovers the interface and constructor via reflection and compiles a constructor delegate.</remarks>
 37    /// <exception cref="InvalidOperationException">The type has zero or multiple state-backed interfaces, or lacks the 
 38    public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
 39    {
 940        Type stateType = GetSingleStateType(typeToConvert);
 41
 742        ConstructorInfo constructor = typeToConvert.GetConstructor(new[] { stateType })
 743            ?? throw new InvalidOperationException(
 744                $"Type '{typeToConvert}' must define a public constructor accepting '{stateType}'.");
 45
 646        Type converterType = typeof(StateJsonConverter<,>).MakeGenericType(typeToConvert, stateType);
 647        Delegate factory = CreateFactory(typeToConvert, stateType, constructor);
 48
 649        return (JsonConverter)Activator.CreateInstance(converterType, factory)!;
 50    }
 51
 52    private static bool HasStateBackedContract(Type type)
 53    {
 9054        foreach (Type interfaceType in type.GetInterfaces())
 55        {
 3456            if (IsStateBackedInterface(interfaceType))
 657                return true;
 58        }
 59
 860        return false;
 61    }
 62
 63    private static Type GetSingleStateType(Type type)
 64    {
 965        Type? stateType = null;
 66
 3567        foreach (Type interfaceType in type.GetInterfaces())
 68        {
 969            if (!IsStateBackedInterface(interfaceType))
 70                continue;
 71
 972            Type currentStateType = interfaceType.GetGenericArguments()[0];
 973            if (stateType != null)
 74            {
 175                throw new InvalidOperationException(
 176                    $"Type '{type}' must implement only one IStateBacked<TState> contract.");
 77            }
 78
 879            stateType = currentStateType;
 80        }
 81
 882        return stateType
 883            ?? throw new InvalidOperationException(
 884                $"Type '{type}' must implement IStateBacked<TState>.");
 85    }
 86
 87    private static bool IsStateBackedInterface(Type type)
 88    {
 4389        return type.IsGenericType
 4390            && type.GetGenericTypeDefinition() == typeof(IStateBacked<>);
 91    }
 92
 93    private static Delegate CreateFactory(Type recordType, Type stateType, ConstructorInfo constructor)
 94    {
 695        ParameterExpression stateParameter = Expression.Parameter(stateType, "state");
 696        NewExpression createRecord = Expression.New(constructor, stateParameter);
 697        Type factoryType = typeof(Func<,>).MakeGenericType(stateType, recordType);
 98
 699        return Expression.Lambda(factoryType, createRecord, stateParameter).Compile();
 100    }
 101}