RaspberryIO_26/Swan.Tiny/Extensions.cs

115 lines
4.8 KiB
C#
Raw Normal View History

2019-12-09 17:25:54 +01:00
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Swan.Lite.Reflection;
using Swan.Mappers;
using Swan.Reflection;
namespace Swan {
/// <summary>
/// Extension methods.
/// </summary>
public static partial class Extensions {
/// <summary>
/// Iterates over the public, instance, readable properties of the source and
/// tries to write a compatible value to a public, instance, writable property in the destination.
/// </summary>
/// <typeparam name="T">The type of the source.</typeparam>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
/// <param name="ignoreProperties">The ignore properties.</param>
/// <returns>
/// Number of properties that was copied successful.
/// </returns>
public static Int32 CopyPropertiesTo<T>(this T source, Object? target, params String[]? ignoreProperties) where T : class => ObjectMapper.Copy(source, target, GetCopyableProperties(target), ignoreProperties);
/// <summary>
/// Copies the properties to new instance of T.
/// </summary>
/// <typeparam name="T">The new object type.</typeparam>
/// <param name="source">The source.</param>
/// <param name="ignoreProperties">The ignore properties.</param>
/// <returns>
/// The specified type with properties copied.
/// </returns>
/// <exception cref="ArgumentNullException">source.</exception>
public static T CopyPropertiesToNew<T>(this Object source, String[]? ignoreProperties = null) where T : class {
if(source == null) {
throw new ArgumentNullException(nameof(source));
}
T target = Activator.CreateInstance<T>();
_ = ObjectMapper.Copy(source, target, GetCopyableProperties(target), ignoreProperties);
return target;
}
/// <summary>
/// Gets the copyable properties.
///
/// If there is no properties with the attribute <c>AttributeCache</c> returns all the properties.
/// </summary>
/// <param name="this">The object.</param>
/// <returns>
/// Array of properties.
/// </returns>
/// <exception cref="ArgumentNullException">model.</exception>
/// <seealso cref="AttributeCache"/>
public static IEnumerable<String> GetCopyableProperties(this Object? @this) {
if(@this == null) {
throw new ArgumentNullException(nameof(@this));
}
global::System.Collections.Generic.IEnumerable<global::System.Reflection.PropertyInfo> collection = PropertyTypeCache.DefaultCache.Value.RetrieveAllProperties(@this.GetType(), true);
global::System.Collections.Generic.IEnumerable<global::System.String> properties = collection.Select(x => new {
x.Name,
HasAttribute = AttributeCache.DefaultCache.Value.RetrieveOne<CopyableAttribute>(x) != null,
}).Where(x => x.HasAttribute).Select(x => x.Name);
return properties.Any() ? properties : collection.Select(x => x.Name);
}
internal static void CreateTarget(this Object source, Type targetType, Boolean includeNonPublic, ref Object? target) {
switch(source) {
// do nothing. Simply skip creation
case String _:
break;
// When using arrays, there is no default constructor, attempt to build a compatible array
case IList sourceObjectList when targetType.IsArray:
Type? elementType = targetType.GetElementType();
if(elementType != null) {
target = Array.CreateInstance(elementType, sourceObjectList.Count);
}
break;
default:
IEnumerable<Tuple<System.Reflection.ConstructorInfo, System.Reflection.ParameterInfo[]>> constructors = ConstructorTypeCache.DefaultCache.Value.RetrieveAllConstructors(targetType, includeNonPublic);
// Try to check if empty constructor is available
if(constructors.Any(x => x.Item2.Length == 0)) {
target = Activator.CreateInstance(targetType, includeNonPublic);
} else {
Tuple<System.Reflection.ConstructorInfo, System.Reflection.ParameterInfo[]> firstCtor = constructors.OrderBy(x => x.Item2.Length).FirstOrDefault();
target = Activator.CreateInstance(targetType, firstCtor?.Item2.Select(arg => arg.GetType().GetDefault()).ToArray());
}
break;
}
}
internal static String GetNameWithCase(this String name, JsonSerializerCase jsonSerializerCase) => jsonSerializerCase switch
{
JsonSerializerCase.PascalCase => Char.ToUpperInvariant(name[0]) + name.Substring(1),
JsonSerializerCase.CamelCase => Char.ToLowerInvariant(name[0]) + name.Substring(1),
JsonSerializerCase.None => name,
_ => throw new ArgumentOutOfRangeException(nameof(jsonSerializerCase), jsonSerializerCase, null)
};
}
}