|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Collections.Immutable; |
| 4 | + |
| 5 | +#nullable enable |
| 6 | +namespace OpenFeature.Model; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Represents the base class for metadata objects. |
| 10 | +/// </summary> |
| 11 | +public abstract class BaseMetadata |
| 12 | +{ |
| 13 | + private readonly ImmutableDictionary<string, object> _metadata; |
| 14 | + |
| 15 | + internal BaseMetadata(Dictionary<string, object> metadata) |
| 16 | + { |
| 17 | + this._metadata = metadata.ToImmutableDictionary(); |
| 18 | + } |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// Gets the boolean value associated with the specified key. |
| 22 | + /// </summary> |
| 23 | + /// <param name="key">The key of the value to retrieve.</param> |
| 24 | + /// <returns>The boolean value associated with the key, or null if the key is not found.</returns> |
| 25 | + public virtual bool? GetBool(string key) |
| 26 | + { |
| 27 | + return this.GetValue<bool>(key); |
| 28 | + } |
| 29 | + |
| 30 | + /// <summary> |
| 31 | + /// Gets the integer value associated with the specified key. |
| 32 | + /// </summary> |
| 33 | + /// <param name="key">The key of the value to retrieve.</param> |
| 34 | + /// <returns>The integer value associated with the key, or null if the key is not found.</returns> |
| 35 | + public virtual int? GetInt(string key) |
| 36 | + { |
| 37 | + return this.GetValue<int>(key); |
| 38 | + } |
| 39 | + |
| 40 | + /// <summary> |
| 41 | + /// Gets the double value associated with the specified key. |
| 42 | + /// </summary> |
| 43 | + /// <param name="key">The key of the value to retrieve.</param> |
| 44 | + /// <returns>The double value associated with the key, or null if the key is not found.</returns> |
| 45 | + public virtual double? GetDouble(string key) |
| 46 | + { |
| 47 | + return this.GetValue<double>(key); |
| 48 | + } |
| 49 | + |
| 50 | + /// <summary> |
| 51 | + /// Gets the string value associated with the specified key. |
| 52 | + /// </summary> |
| 53 | + /// <param name="key">The key of the value to retrieve.</param> |
| 54 | + /// <returns>The string value associated with the key, or null if the key is not found.</returns> |
| 55 | + public virtual string? GetString(string key) |
| 56 | + { |
| 57 | + var hasValue = this._metadata.TryGetValue(key, out var value); |
| 58 | + if (!hasValue) |
| 59 | + { |
| 60 | + return null; |
| 61 | + } |
| 62 | + |
| 63 | + return value as string ?? null; |
| 64 | + } |
| 65 | + |
| 66 | + private T? GetValue<T>(string key) where T : struct |
| 67 | + { |
| 68 | + var hasValue = this._metadata.TryGetValue(key, out var value); |
| 69 | + if (!hasValue) |
| 70 | + { |
| 71 | + return null; |
| 72 | + } |
| 73 | + |
| 74 | + return value is T tValue ? tValue : null; |
| 75 | + } |
| 76 | +} |
0 commit comments