| | 1 | | using System.Linq.Expressions; |
| | 2 | | using System.Reflection; |
| | 3 | |
|
| | 4 | | namespace Fluorite.Strainer.Services.Metadata; |
| | 5 | |
|
| | 6 | | /// <summary> |
| | 7 | | /// Provides <see cref="PropertyInfo"/> and full member name when supplied |
| | 8 | | /// with an <see cref="Expression{TDelegate}"/>. |
| | 9 | | /// </summary> |
| | 10 | | public class PropertyInfoProvider : IPropertyInfoProvider |
| | 11 | | { |
| 24 | 12 | | private readonly BindingFlags _bindingFlags = BindingFlags.Instance | BindingFlags.Public; |
| | 13 | |
|
| | 14 | | public PropertyInfo GetPropertyInfo(Type type, string name) |
| | 15 | | { |
| 1 | 16 | | Guard.Against.Null(type); |
| 1 | 17 | | Guard.Against.NullOrWhiteSpace(name); |
| | 18 | |
|
| 1 | 19 | | return type.GetProperty(name, _bindingFlags); |
| | 20 | | } |
| | 21 | |
|
| | 22 | | /// <inheritdoc/> |
| | 23 | | /// <exception cref="ArgumentNullException"> |
| | 24 | | /// <paramref name="expression"/> is <see langword="null"/>. |
| | 25 | | /// </exception> |
| | 26 | | /// <exception cref="ArgumentException"> |
| | 27 | | /// <paramref name="expression"/> is invalid expression, |
| | 28 | | /// not leading to a readable property. |
| | 29 | | /// </exception> |
| | 30 | | public (PropertyInfo PropertyInfo, string FullName) GetPropertyInfoAndFullName<T>(Expression<Func<T, object>> expres |
| | 31 | | { |
| 10 | 32 | | Guard.Against.Null(expression); |
| | 33 | |
|
| | 34 | | MemberExpression? body; |
| 10 | 35 | | if (expression.Body is MemberExpression) |
| | 36 | | { |
| 6 | 37 | | body = expression.Body as MemberExpression; |
| | 38 | | } |
| | 39 | | else |
| | 40 | | { |
| 4 | 41 | | var ubody = expression.Body as UnaryExpression; |
| 4 | 42 | | body = ubody?.Operand as MemberExpression; |
| | 43 | | } |
| | 44 | |
|
| 10 | 45 | | if (body?.Member is not PropertyInfo propertyInfo) |
| | 46 | | { |
| 2 | 47 | | throw new ArgumentException( |
| 2 | 48 | | $"Expression for '{nameof(T)}' {expression} " + |
| 2 | 49 | | $"is not a valid expression leading to a readable property."); |
| | 50 | | } |
| | 51 | |
|
| 8 | 52 | | var stack = new Stack<string>(); |
| | 53 | |
|
| 16 | 54 | | while (body != null) |
| | 55 | | { |
| 8 | 56 | | stack.Push(body.Member.Name); |
| 8 | 57 | | body = body.Expression as MemberExpression; |
| | 58 | | } |
| | 59 | |
|
| 8 | 60 | | var fullName = string.Join(".", stack.ToArray()); |
| | 61 | |
|
| 8 | 62 | | return (propertyInfo, fullName); |
| | 63 | | } |
| | 64 | |
|
| | 65 | | public PropertyInfo[] GetPropertyInfos(Type type) |
| | 66 | | { |
| 1 | 67 | | Guard.Against.Null(type); |
| | 68 | |
|
| 1 | 69 | | return type.GetProperties(_bindingFlags); |
| | 70 | | } |
| | 71 | | } |