< Summary

Information
Class: ArturRios.Util.WebApi.Configuration.WebApiParameters
Assembly: ArturRios.Util.WebApi
File(s): /home/runner/work/dotnet-webapi-util/dotnet-webapi-util/src/Configuration/WebApiParameters.cs
Line coverage
100%
Covered lines: 45
Uncovered lines: 0
Coverable lines: 45
Total lines: 130
Line coverage: 100%
Branch coverage
88%
Covered branches: 30
Total branches: 34
Branch coverage: 88.2%
Method coverage
100%
Covered methods: 11
Fully covered methods: 11
Total methods: 11
Method coverage: 100%
Full method coverage: 100%

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)87.5%2424100%
get_Args()100%11100%
get_EnvironmentName()100%11100%
get_UseAppSettings()100%11100%
get_UseEnvFile()100%11100%
get_EnableSwaggerDocs()100%11100%
get_SwaggerEnvironments()100%11100%
GetSwaggerEnvironments()75%44100%
IsSwaggerAllowed(...)100%44100%
ToWebApplicationOptions()100%22100%

File(s)

/home/runner/work/dotnet-webapi-util/dotnet-webapi-util/src/Configuration/WebApiParameters.cs

#LineLine coverage
 1using ArturRios.Configuration.Enums;
 2using ArturRios.Extensions;
 3using Microsoft.AspNetCore.Builder;
 4
 5namespace ArturRios.Util.WebApi.Configuration;
 6
 7/// <summary>Startup parameters parsed from command-line arguments (e.g. <c>Environment:Production</c>,
 8/// <c>EnableSwaggerDocs:false</c>), controlling how the application is configured by <see cref="WebApiStartup"/> or
 9/// by the <see cref="WebApplicationBuilderExtensions"/> it is built from.</summary>
 10public class WebApiParameters
 11{
 112    private static readonly string[] DefaultSwaggerEnvironments =
 113        [nameof(EnvironmentType.Development), nameof(EnvironmentType.Local)];
 14
 15    /// <summary>Parses <paramref name="args"/> into the corresponding properties. Keys are case-insensitive;
 16    /// unrecognized or malformed entries are ignored, leaving the default values in place.</summary>
 17    /// <param name="args">The command-line arguments, each in <c>Key:Value</c> form.</param>
 3418    public WebApiParameters(string[] args)
 19    {
 3420        Args = args;
 21
 3422        if (args.IsEmpty())
 23        {
 524            return;
 25        }
 26
 19827        foreach (var arg in args)
 28        {
 7029            var parts = arg.Split(':', 2, StringSplitOptions.TrimEntries);
 30
 7031            if (parts.Length != 2)
 32            {
 33                continue;
 34            }
 35
 7036            var key = parts[0];
 7037            var value = parts[1];
 38
 7039            switch (key.ToLowerInvariant())
 40            {
 41                case "environment":
 2142                    EnvironmentName = value.IsValidEnumValue<EnvironmentType>() ? value : string.Empty;
 2143                    break;
 44                case "enableswaggerdocs":
 245                    EnableSwaggerDocs = value.ParseToBoolOrDefault(true)!.Value;
 246                    break;
 47                case "useappsettings":
 48                case "useappsetting":
 2349                    UseAppSettings = value.ParseToBoolOrDefault(true)!.Value;
 2350                    break;
 51                case "useenvfile":
 2252                    UseEnvFile = value.ParseToBoolOrDefault(true)!.Value;
 2253                    break;
 54                case "swaggerenvironments":
 255                    if (value.StartsWith('[') && value.EndsWith(']'))
 56                    {
 257                        SwaggerEnvironments = value.Trim('[', ']').Split(
 258                            ',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 59                    }
 60
 61                    break;
 62            }
 63        }
 2964    }
 65
 66    /// <summary>The command-line arguments these parameters were parsed from.</summary>
 2267    public string[] Args { get; }
 68
 69    /// <summary>The environment name (e.g. <c>Development</c>, <c>Production</c>), if a valid one was supplied.
 70    /// When set, <see cref="ToWebApplicationOptions"/> makes it the host environment, overriding
 71    /// <c>ASPNETCORE_ENVIRONMENT</c>.</summary>
 9972    public string EnvironmentName { get; set; } = string.Empty;
 73
 74    /// <summary>Whether <c>appsettings.json</c> should be loaded. Defaults to <c>true</c>. Parsed from the
 75    /// <c>UseAppSettings</c> argument (or its legacy spelling, <c>UseAppSetting</c>).</summary>
 8176    public bool UseAppSettings { get; set; } = true;
 77
 78    /// <summary>Whether a <c>.env</c> file should be loaded. Defaults to <c>true</c>.</summary>
 7879    public bool UseEnvFile { get; set; } = true;
 80
 81    /// <summary>Parsed from the <c>EnableSwaggerDocs</c> argument. When <c>false</c>, Swagger is neither generated
 82    /// nor served in any environment, whatever <see cref="SwaggerEnvironments"/> says (see
 83    /// <see cref="IsSwaggerAllowed"/>). Defaults to <c>true</c>, leaving Swagger gated by environment.</summary>
 6384    public bool EnableSwaggerDocs { get; set; } = true;
 85
 86    /// <summary>The environment names in which Swagger should be enabled, as parsed from the <c>SwaggerEnvironments</c>
 6287    public string[] SwaggerEnvironments { get; set; } = [];
 88
 89    /// <summary>Returns the configured Swagger environments, falling back to <c>Development</c> and <c>Local</c>
 90    /// when none were supplied or none are valid.</summary>
 91    public string[] GetSwaggerEnvironments()
 92    {
 2493        if (SwaggerEnvironments.IsEmpty())
 94        {
 2395            return [.. DefaultSwaggerEnvironments];
 96        }
 97
 398        var validEnvs = SwaggerEnvironments.Where(env => env.IsValidEnumValue<EnvironmentType>()).ToArray();
 99
 1100        return validEnvs.IsNotEmpty() ? validEnvs : [.. DefaultSwaggerEnvironments];
 101    }
 102
 103    /// <summary>Whether Swagger is allowed in <paramref name="environmentName"/>. Never when the
 104    /// <c>EnableSwaggerDocs:false</c> argument was supplied; otherwise when the environment is in
 105    /// <paramref name="allowedEnvironments"/>, if non-empty, or else in <see cref="GetSwaggerEnvironments"/>.</summary>
 106    /// <param name="environmentName">The current host environment name.</param>
 107    /// <param name="allowedEnvironments">Optional explicit list of environments in which Swagger is allowed.</param>
 108    public bool IsSwaggerAllowed(string environmentName, EnvironmentType[]? allowedEnvironments = null)
 109    {
 25110        if (!EnableSwaggerDocs)
 111        {
 2112            return false;
 113        }
 114
 23115        var environments = allowedEnvironments.IsNotEmpty()
 2116            ? allowedEnvironments!.Select(env => env.ToString())
 23117            : GetSwaggerEnvironments();
 118
 23119        return environments.Contains(environmentName, StringComparer.OrdinalIgnoreCase);
 120    }
 121
 122    /// <summary>Builds the <see cref="WebApplicationOptions"/> for <c>WebApplication.CreateBuilder</c>: the
 123    /// original <see cref="Args"/>, and <see cref="EnvironmentName"/> as the environment when one was supplied.</summar
 124    public WebApplicationOptions ToWebApplicationOptions() =>
 22125        new()
 22126        {
 22127            Args = Args,
 22128            EnvironmentName = string.IsNullOrWhiteSpace(EnvironmentName) ? null : EnvironmentName
 22129        };
 130}