-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathPathVisitor.cs
More file actions
53 lines (44 loc) · 1.72 KB
/
PathVisitor.cs
File metadata and controls
53 lines (44 loc) · 1.72 KB
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
52
53
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace JSONAPI.Core
{
/// <summary>
/// Utility for converting an property expression into a dot-separated path string
/// </summary>
public class PathVisitor : ExpressionVisitor
{
private readonly IResourceTypeRegistry _resourceTypeRegistry;
/// <summary>
/// Creates a new PathVisitor
/// </summary>
/// <param name="resourceTypeRegistry"></param>
public PathVisitor(IResourceTypeRegistry resourceTypeRegistry)
{
_resourceTypeRegistry = resourceTypeRegistry;
}
private readonly Stack<string> _segments = new Stack<string>();
public string Path { get { return string.Join(".", _segments.ToArray()); } }
protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (node.Method.Name == "Select")
{
Visit(node.Arguments[1]);
Visit(node.Arguments[0]);
}
return node;
}
protected override Expression VisitMember(MemberExpression node)
{
var property = node.Member as PropertyInfo;
if (property == null) return node;
var registration = _resourceTypeRegistry.GetRegistrationForType(property.DeclaringType);
if (registration == null || registration.Relationships == null) return node;
var relationship = registration.Relationships.FirstOrDefault(r => r.Property == property);
if (relationship == null) return node;
_segments.Push(relationship.JsonKey);
return base.VisitMember(node);
}
}
}