summaryrefslogtreecommitdiff
path: root/FireBase/Offline/Internals/MemberAccessVisitor.cs
blob: 89a77daf71c922f236cbd9a0e4b927c70a9fc9c7 (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
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using Newtonsoft.Json;

namespace Firebase.Database.Offline.Internals
{
    public class MemberAccessVisitor : ExpressionVisitor
    {
        private readonly IList<string> propertyNames = new List<string>();

        private bool wasDictionaryAccess;

        public IEnumerable<string> PropertyNames => propertyNames;

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

                    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();
                    propertyNames.Add(e.DynamicInvoke().ToString());
                    wasDictionaryAccess = callExpr.Arguments[0].NodeType == ExpressionType.MemberAccess;
                }
            }

            return base.Visit(expr);
        }
    }
}