| | 1 | | using Fluorite.Strainer.Models.Sorting; |
| | 2 | | using Fluorite.Strainer.Models.Sorting.Terms; |
| | 3 | | using Fluorite.Strainer.Services.Configuration; |
| | 4 | | using System.Linq.Expressions; |
| | 5 | |
|
| | 6 | | namespace Fluorite.Strainer.Services.Sorting; |
| | 7 | |
|
| | 8 | | public class CustomSortingExpressionProvider : ICustomSortingExpressionProvider |
| | 9 | | { |
| | 10 | | private readonly IConfigurationCustomMethodsProvider _configurationCustomMethodsProvider; |
| | 11 | |
|
| 5 | 12 | | public CustomSortingExpressionProvider(IConfigurationCustomMethodsProvider configurationCustomMethodsProvider) |
| | 13 | | { |
| 5 | 14 | | _configurationCustomMethodsProvider = Guard.Against.Null(configurationCustomMethodsProvider); |
| 5 | 15 | | } |
| | 16 | |
|
| | 17 | | public bool TryGetCustomExpression<T>( |
| | 18 | | ISortTerm sortTerm, |
| | 19 | | bool isSubsequent, |
| | 20 | | out ISortExpression<T>? sortExpression) |
| | 21 | | { |
| 4 | 22 | | Guard.Against.Null(sortTerm); |
| | 23 | |
|
| 4 | 24 | | if (!TryGetCustomSortingMethod<T>(sortTerm, out var customMethod)) |
| | 25 | | { |
| 2 | 26 | | sortExpression = null; |
| | 27 | |
|
| 2 | 28 | | return false; |
| | 29 | | } |
| | 30 | |
|
| 2 | 31 | | var expression = GetExpression(sortTerm, (ICustomSortMethod<T>)customMethod!); |
| 2 | 32 | | sortExpression = new SortExpression<T>(expression) |
| 2 | 33 | | { |
| 2 | 34 | | IsDefault = false, |
| 2 | 35 | | IsDescending = sortTerm.IsDescending, |
| 2 | 36 | | IsSubsequent = isSubsequent, |
| 2 | 37 | | }; |
| | 38 | |
|
| 2 | 39 | | return true; |
| | 40 | | } |
| | 41 | |
|
| | 42 | | private Expression<Func<T, object>> GetExpression<T>(ISortTerm sortTerm, ICustomSortMethod<T> customSortMethod) |
| | 43 | | { |
| 2 | 44 | | return customSortMethod.ExpressionProvider != null |
| 2 | 45 | | ? customSortMethod.ExpressionProvider(sortTerm) |
| 2 | 46 | | : customSortMethod.Expression!; |
| | 47 | | } |
| | 48 | |
|
| | 49 | | private bool TryGetCustomSortingMethod<T>(ISortTerm sortTerm, out ICustomSortMethod? customMethod) |
| | 50 | | { |
| 4 | 51 | | customMethod = null; |
| | 52 | |
|
| 4 | 53 | | return _configurationCustomMethodsProvider.GetCustomSortMethods().TryGetValue(typeof(T), out var customSortMetho |
| 4 | 54 | | && customSortMethods.TryGetValue(sortTerm.Name, out customMethod); |
| | 55 | | } |
| | 56 | | } |