95 lines
3.3 KiB
C#
95 lines
3.3 KiB
C#
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<string, IFeature> Features { get; }
|
|
|
|
private static readonly Lazy<FeatureContext> instance;
|
|
public static FeatureContext Instance => instance.Value;
|
|
|
|
static FeatureContext()
|
|
{
|
|
instance = new Lazy<FeatureContext>(() => new FeatureContext((FeatureConfigurationSection)ConfigurationManager.GetSection(Constants.ConfigurationSectionNames.FeatureConfig)));
|
|
}
|
|
|
|
public FeatureContext(FeatureConfigurationSection config)
|
|
{
|
|
Features = GetFeaturesFromConfig(config);
|
|
}
|
|
|
|
private static Dictionary<string, IFeature> GetFeaturesFromConfig(FeatureConfigurationSection config)
|
|
{
|
|
var features = new Dictionary<string, IFeature>();
|
|
|
|
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<string> 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<string> 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;
|
|
}
|
|
}
|
|
}
|