All Downloads are FREE. Search and download functionalities are using the official Maven repository.

csharp-functions.OpenApi.TypeExtensions.mustache Maven / Gradle / Ivy

There is a newer version: 7.6.0
Show newest version
using System;
using System.Linq;
using System.Text;

namespace {{packageName}}.OpenApi
{
    /// 
    /// Replacement utilities from Swashbuckle.AspNetCore.SwaggerGen which are not in 5.x
    /// 
    public static class TypeExtensions
    {
        /// 
        /// Produce a friendly name for the type which is unique.
        /// 
        /// 
        /// 
        public static string FriendlyId(this Type type, bool fullyQualified = false)
        {
            var typeName = fullyQualified
                ? type.FullNameSansTypeParameters().Replace("+", ".")
                : type.Name;

            if (type.IsGenericType)
            {
                var genericArgumentIds = type.GetGenericArguments()
                    .Select(t => t.FriendlyId(fullyQualified))
                    .ToArray();

                return new StringBuilder(typeName)
                    .Replace($"`{genericArgumentIds.Count()}", string.Empty)
                    .Append($"[{string.Join(",", genericArgumentIds).TrimEnd(',')}]")
                    .ToString();
            }

            return typeName;
        }

        /// 
        /// Determine the fully qualified type name without type parameters.
        /// 
        /// 
        public static string FullNameSansTypeParameters(this Type type)
        {
            var fullName = type.FullName;
            if (string.IsNullOrEmpty(fullName))
                fullName = type.Name;
            var chopIndex = fullName.IndexOf("[[", StringComparison.Ordinal);
            return (chopIndex == -1) ? fullName : fullName.Substring(0, chopIndex);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy