summaryrefslogtreecommitdiff
path: root/FireBase/Offline/Internals/MemberAccessVisitor.cs
blob: 1f7cb118986d3dd5cd8dbd03862d8df1737a1561 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
namespace Firebase.Database.Offline.Internals
{
    using System.Collections.Generic;
    using System.Linq.Expressions;
    using System.Reflection;

    using Newtonsoft.Json;

    public class MemberAccessVisitor : ExpressionVisitor
    {
        private readonly IList<string> propertyNames = new List<string>();

        private bool wasDictionaryAccess;

        public IEnumerable<string> PropertyNames => this.propertyNames;

        public MemberAccessVisitor()
        {
        }

        public override Expression Visit(Expression expr)
        {
            if (expr?.NodeType == ExpressionType.MemberAccess)
            {
                if (this.wasDictionaryAccess)
                {
                    this.wasDictionaryAccess = false;
                }
                else
                {
                    var memberExpr = (MemberExpression)expr;
                    var jsonAttr = memberExpr.Member.GetCustomAttribute<JsonPropertyAttribute>();

                    this.propertyNames.Add(jsonAttr?.PropertyName ?? memberExpr.Member.Name);
                }
            }
            else if (expr?.NodeType == ExpressionType.Call)
            {
                var callExpr = (MethodCallExpression)expr;
                if (callExpr.Method.Name == "get_Item" && callExpr.Arguments.Count == 1)
                {
                    var e = Expression.Lambda(callExpr.Arguments[0]).Compile();
                    this.propertyNames.Add(e.DynamicInvoke().ToString());
                    this.wasDictionaryAccess = callExpr.Arguments[0].NodeType == ExpressionType.MemberAccess;
                }
            }

            return base.Visit(expr);
        }
    }
}