12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- using System;
- 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, ILuObjectConverterOptions 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.DescriptorOptions);
- 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);
- }
- }
- }
|