| 
 | 1 | +// Copyright (c) Microsoft Corporation. All rights reserved.  | 
 | 2 | +// Licensed under the MIT license.  | 
 | 3 | + | 
 | 4 | +using System;  | 
 | 5 | +using System.Collections.Generic;  | 
 | 6 | +using System.Text.Json.Nodes;  | 
 | 7 | +using Microsoft.OpenApi.Interfaces;  | 
 | 8 | + | 
 | 9 | +namespace Microsoft.OpenApi.Any  | 
 | 10 | +{  | 
 | 11 | +    /// <summary>  | 
 | 12 | +    /// A dictionary of OpenApi extensions.  | 
 | 13 | +    /// </summary>  | 
 | 14 | +    public class OpenApiExtensionDictionary : Dictionary<string, IOpenApiExtension>  | 
 | 15 | +    {  | 
 | 16 | +        /// <summary>  | 
 | 17 | +        /// Override the base class indexer to return OpenApiAny.  | 
 | 18 | +        /// </summary>  | 
 | 19 | +        /// <param name="key"></param>  | 
 | 20 | +        /// <returns></returns>  | 
 | 21 | +        public new OpenApiAny this[string key]  | 
 | 22 | +        {             | 
 | 23 | +            get => (OpenApiAny)base[key];  | 
 | 24 | +            set => base[key] = ConvertIfJsonNode(value);  | 
 | 25 | +        }  | 
 | 26 | + | 
 | 27 | +        /// <summary>  | 
 | 28 | +        /// Adds an extension to the dictionary.  | 
 | 29 | +        /// </summary>  | 
 | 30 | +        /// <param name="key"></param>  | 
 | 31 | +        /// <param name="value"></param>  | 
 | 32 | +        public void Add(string key, object value)  | 
 | 33 | +        {  | 
 | 34 | +            base.Add(key, ConvertIfJsonNode(value));  | 
 | 35 | +        }  | 
 | 36 | + | 
 | 37 | +        private static IOpenApiExtension ConvertIfJsonNode(object? value)  | 
 | 38 | +        {  | 
 | 39 | +            return value switch  | 
 | 40 | +            {  | 
 | 41 | +                IOpenApiExtension extension => extension,  | 
 | 42 | +                JsonNode node => (OpenApiAny)node,  | 
 | 43 | +                _ => throw new InvalidOperationException($"Cannot convert value of type '{value?.GetType().Name}' to IOpenApiExtension.")  | 
 | 44 | +            };  | 
 | 45 | +        }  | 
 | 46 | + | 
 | 47 | +        /// <summary>  | 
 | 48 | +        /// Test the OpenApiExtensionDictionary and base class implementations.  | 
 | 49 | +        /// </summary>  | 
 | 50 | +        public static void TestExtensions()  | 
 | 51 | +        {  | 
 | 52 | +            var jsonNode = new JsonObject();  | 
 | 53 | +            var extensions = new OpenApiExtensionDictionary  | 
 | 54 | +            {  | 
 | 55 | +                ["x-key"] = jsonNode  | 
 | 56 | +            };  | 
 | 57 | +            extensions.Add("x-key", jsonNode);  | 
 | 58 | +            var extensions2 = new Dictionary<string, IOpenApiExtension>  | 
 | 59 | +            {  | 
 | 60 | +                ["x-key"] = (OpenApiAny)jsonNode  | 
 | 61 | +            };  | 
 | 62 | +            extensions2.Add("x-key", (OpenApiAny)jsonNode);  | 
 | 63 | +        }  | 
 | 64 | +    }  | 
 | 65 | +}  | 
0 commit comments