12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using Luticate2.Auth.Utils.Dbo;
- using Luticate2.Auth.Utils.Dbo.Fields;
- using Luticate2.Auth.Utils.Dbo.Result;
- using Luticate2.Auth.Utils.Interfaces;
-
- namespace Luticate2.Auth.Utils.Business.Converters.ObjectConverter
- {
- public class LuObjectConverterLists : ILuObjectConverter
- {
- protected IServiceProvider ServiceProvider { get; }
-
- public LuObjectConverterLists(IServiceProvider serviceProvider)
- {
- ServiceProvider = serviceProvider;
- }
-
- public LuResult<object> Convert(object srcObj, object dstObj, LuFieldDbo path, LuPartialFieldsDbo fields, ILuObjectConverterOptions options)
- {
- var dstObjType = dstObj.GetType();
- var addMethodInfo = dstObjType.GetMethod(nameof(ICollection<object>.Add));
- if (addMethodInfo == null)
- {
- return LuResult<object>.Error(LuStatus.InternalError.ToInt(),
- $"Could not find get method info {nameof(ICollection)}.{nameof(ICollection<object>.Add)} for type {dstObjType}");
- }
-
- if (srcObj is IEnumerable enumerable)
- {
- foreach (var subSrcObj in enumerable)
- {
- object convertedObj = null;
- if (subSrcObj != null)
- {
- var typeFrom = subSrcObj.GetType();
-
- var typeToResult = options.TypeConverter.ConvertType(typeFrom);
- if (!typeToResult)
- {
- return typeToResult.To<object>();
- }
- var typeTo = typeToResult.Data;
-
- var converterResult = LuObjectConverterUtils.GetObjectConverter(ServiceProvider, typeFrom, typeTo);
- if (!converterResult)
- {
- return converterResult.To<object>();
- }
- var converter = converterResult.Data;
-
- var subDstObjResult = options.Allocator.GetInstance(typeTo);
- if (!subDstObjResult)
- {
- return subDstObjResult.To<object>();
- }
- var subDstObj = subDstObjResult.Data;
-
- var convertResult = converter.Convert(subSrcObj, subDstObj, path, fields, options);
- if (!convertResult)
- {
- return convertResult;
- }
- convertedObj = convertResult.Data;
- }
-
- addMethodInfo.Invoke(dstObj, new []{convertedObj});
- }
-
- return LuResult<object>.Ok(dstObj);
- }
- else
- {
- return LuResult<object>.Error(LuStatus.InputError.ToInt(), $"Could not convert {nameof(srcObj)} to {nameof(IEnumerable)}");
- }
- }
- }
- }
|