1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- using System;
- using Luticate2.Auth.Utils.Business.Converters;
- 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, LuPartialFieldsDbo fields, LuConvertersOptions options)
- {
- // TODO Check if this is correct
- 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())
- {
- // TODO check if field is included in fields
- // TODO Handle srcPropExpression == null
- var srcPropExpression = descriptor.GetMemberValueExpression(memberInfo, options);
- var srcPropDelegate = srcPropExpression.Compile();
- var srcProp = srcPropDelegate.DynamicInvoke(srcObj);
- var srcType = srcProp != null ? srcProp.GetType() : srcPropExpression.ReturnType;
- var dstType = memberInfo.GetUnderlyingType();
-
- // TODO Handle objectConverter == null
- var objectConverter = LuObjectConverterUtils.GetObjectConverter(ServiceProvider, srcType, dstType);
- var dstPropResult = objectConverter.Convert(srcProp, 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);
- }
- }
- }
|