123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- using System;
- using Luticate2.Auth.Utils.Business.Fields;
- using Luticate2.Auth.Utils.Business.Utils;
- using Luticate2.Auth.Utils.Dbo.Fields;
- using Luticate2.Auth.Utils.Dbo.Result;
- using Luticate2.Auth.Utils.Interfaces;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace Luticate2.Auth.Utils.Business.ObjectConverter
- {
- public class LuObjectConverterPoco<TTypeFrom, TTypeTo> : ILuObjectConverter<TTypeFrom, TTypeTo>
- {
- protected IServiceProvider ServiceProvider { get; }
-
- public LuObjectConverterPoco(IServiceProvider serviceProvider)
- {
- ServiceProvider = serviceProvider;
- }
-
- public LuResult<object> Convert(object srcObj, object dstObj, LuFieldDbo path, LuPartialFieldsDbo fields, ILuObjectConverterOptions options)
- {
- if (srcObj == null)
- {
- return LuResult<object>.Ok(default(TTypeTo));
- }
- // TODO Handle descriptor == null
- var descriptor = ServiceProvider.GetService<ILuObjectConverterDescriptor<TTypeTo, TTypeFrom>>();
- var typeTo = typeof(TTypeTo);
- // var dstObj = options.Allocator.GetInstance(typeTo);
-
- foreach (var memberInfo in typeTo.GetProperties())
- {
- var memberPath = LuFieldDbo.Make(path).Add(memberInfo.Name);
- if (!fields.Fields.IsIncluded(memberPath))
- {
- continue;
- }
- // TODO Handle srcPropExpression == null
- var subSrcPropExpression = descriptor.GetMemberValueExpression(memberInfo, options.DescriptorOptions);
- var subSrcPropDelegate = subSrcPropExpression.Compile();
- var subSrcProp = subSrcPropDelegate.DynamicInvoke(srcObj);
- var subSrcType = subSrcProp != null ? subSrcProp.GetType() : subSrcPropExpression.ReturnType;
- var subDstType = memberInfo.GetUnderlyingType();
-
- // TODO Handle objectConverter == null
- var objectConverter = LuObjectConverterUtils.GetObjectConverter(ServiceProvider, subSrcType, subDstType);
- var subDstObj = options.Allocator.GetInstance(subDstType);
- var dstPropResult = objectConverter.Convert(subSrcProp, subDstObj, memberPath, fields, options);
- if (!dstPropResult)
- {
- return dstPropResult;
- }
-
- var dstProp = dstPropResult.Data;
-
- var result = LuExpressionUtils.SetValueFromMember(memberInfo, dstObj, dstProp);
- if (!result)
- {
- return result.To<object>();
- }
- }
-
- return LuResult<object>.Ok(dstObj);
- }
- }
- }
|