using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using Kreta.Core.FeatureToggle.Configuration; namespace Kreta.Core.FeatureToggle { public class FeatureContext : IFeatureContext { private Dictionary Features { get; } private static readonly Lazy instance; public static FeatureContext Instance => instance.Value; static FeatureContext() { instance = new Lazy(() => new FeatureContext((FeatureConfigurationSection)ConfigurationManager.GetSection(Constants.ConfigurationSectionNames.FeatureConfig))); } public FeatureContext(FeatureConfigurationSection config) { Features = GetFeaturesFromConfig(config); } private static Dictionary GetFeaturesFromConfig(FeatureConfigurationSection config) { var features = new Dictionary(); foreach (SimpleFeatureConfiguration featureConfiguration in config.SimpleFeatures) { var feature = new SimpleFeature { Name = featureConfiguration.Name, IsEnabled = featureConfiguration.IsEnabled, InstituteIds = featureConfiguration.InstituteIds, Environments = featureConfiguration.Environments }; features[feature.Name] = feature; } return features; } public bool IsEnabled(string featureName, string environment = null, string instituteId = null, List instituteIds = null) { if (string.IsNullOrWhiteSpace(featureName)) { throw new ArgumentException($"{nameof(featureName)} null vagy üres"); } if (!Features.ContainsKey(featureName)) { throw new ArgumentException($"{featureName} nem létező feature"); } bool isFeatureEnabled = Features[featureName].IsEnabled; if (isFeatureEnabled && (!string.IsNullOrWhiteSpace(environment) || !string.IsNullOrWhiteSpace(instituteId))) { IFeature feature = Features[featureName]; return CheckEnvironment(feature, environment) && CheckInstituteId(feature, instituteId, instituteIds); } return isFeatureEnabled; } private bool CheckEnvironment(IFeature feature, string environment) { if (!string.IsNullOrWhiteSpace(environment)) { return !feature.Environments.Any() || feature.Environments.Contains(environment); } return true; } private bool CheckInstituteId(IFeature feature, string instituteId, List instituteIds = null) { if (!string.IsNullOrWhiteSpace(instituteId)) { if (instituteIds != null && instituteIds.Any()) { return instituteIds.Contains(instituteId, StringComparer.InvariantCultureIgnoreCase); } return !feature.InstituteIds.Any() || feature.InstituteIds.Contains(instituteId, StringComparer.InvariantCultureIgnoreCase); } return true; } } }