using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq.Expressions; using System.Text; using System.Linq; namespace FreeSql { public interface IDataFilter where TEntity : class { IDataFilter Apply(string filterName, Expression> filterAndValidateExp); IDataFilter Enable(params string[] filterName); IDataFilter EnableAll(); IDataFilter Disable(params string[] filterName); IDataFilter DisableAll(); bool IsEnabled(string filterName); } internal class DataFilter : IDataFilter where TEntity : class { internal class FilterItem { public Expression> Expression { get; set; } Func _expressionDelegate; public Func ExpressionDelegate => _expressionDelegate ?? (_expressionDelegate = Expression?.Compile()); public bool IsEnabled { get; set; } } internal ConcurrentDictionary _filters = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); public IDataFilter Apply(string filterName, Expression> filterAndValidateExp) { if (filterName == null) throw new ArgumentNullException(nameof(filterName)); if (filterAndValidateExp == null) return this; var filterItem = new FilterItem { Expression = filterAndValidateExp, IsEnabled = true }; _filters.AddOrUpdate(filterName, filterItem, (k, v) => filterItem); return this; } public IDataFilter Disable(params string[] filterName) { if (filterName == null || filterName.Any() == false) return this; foreach (var name in filterName) { if (_filters.TryGetValue(name, out var tryfi)) tryfi.IsEnabled = false; } return this; } public IDataFilter DisableAll() { foreach (var val in _filters.Values.ToArray()) val.IsEnabled = false; return this; } public IDataFilter Enable(params string[] filterName) { if (filterName == null || filterName.Any() == false) return this; foreach (var name in filterName) { if (_filters.TryGetValue(name, out var tryfi)) tryfi.IsEnabled = true; } return this; } public IDataFilter EnableAll() { foreach (var val in _filters.Values.ToArray()) val.IsEnabled = true; return this; } public bool IsEnabled(string filterName) { if (filterName == null) return false; return _filters.TryGetValue(filterName, out var tryfi) ? tryfi.IsEnabled : false; } } public class GlobalDataFilter { internal List<(Type type, string name, LambdaExpression exp)> _filters = new List<(Type type, string name, LambdaExpression exp)>(); public GlobalDataFilter Apply(string filterName, Expression> filterAndValidateExp) where TEntity : class { if (filterName == null) throw new ArgumentNullException(nameof(filterName)); if (filterAndValidateExp == null) return this; _filters.Add((typeof(TEntity), filterName, filterAndValidateExp)); return this; } } }