This repository was archived by the owner on Nov 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathSchemaReferenceRegistry.cs
377 lines (313 loc) · 15.4 KB
/
SchemaReferenceRegistry.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using System.Xml.Serialization;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Exceptions;
using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Extensions;
using Microsoft.OpenApi.Models;
namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.ReferenceRegistries
{
/// <summary>
/// Reference Registry for <see cref="OpenApiSchema"/>
/// </summary>
public class SchemaReferenceRegistry : ReferenceRegistry<Type, OpenApiSchema>
{
private readonly SchemaGenerationSettings _schemaGenerationSettings;
private IPropertyNameResolver _propertyNameResolver;
private readonly Dictionary<string, string> _propertyDescriptionMap = new Dictionary<string, string>();
/// <summary>
/// Creates an instance of <see cref="SchemaReferenceRegistry"/>.
/// </summary>
/// <param name="schemaGenerationSettings">The schema generation settings.</param>
public SchemaReferenceRegistry(SchemaGenerationSettings schemaGenerationSettings)
{
_schemaGenerationSettings = schemaGenerationSettings
?? throw new ArgumentNullException(nameof(schemaGenerationSettings));
_propertyNameResolver = schemaGenerationSettings.PropertyNameResolver;
}
/// <summary>
/// Creates an instance of <see cref="SchemaReferenceRegistry"/>.
/// </summary>
/// <param name="schemaGenerationSettings">The schema generation settings.</param>
/// <param name="propertyDescriptionMap">The property description map.</param>
public SchemaReferenceRegistry( SchemaGenerationSettings schemaGenerationSettings,
Dictionary<string, string> propertyDescriptionMap )
{
_schemaGenerationSettings = schemaGenerationSettings
?? throw new ArgumentNullException( nameof( schemaGenerationSettings ) );
_propertyNameResolver = schemaGenerationSettings.PropertyNameResolver;
_propertyDescriptionMap = propertyDescriptionMap
?? throw new ArgumentNullException( nameof( propertyDescriptionMap ) );
}
/// <summary>
/// The dictionary containing all references of the given type.
/// </summary>
public override IDictionary<string, OpenApiSchema> References { get; } =
new Dictionary<string, OpenApiSchema>();
/// <summary>
/// Finds the existing reference object based on the key from the input or creates a new one.
/// </summary>
/// <returns>The existing or created reference object.</returns>
internal override OpenApiSchema FindOrAddReference(Type input)
{
// Return empty schema when the type does not have a name.
// This can occur, for example, when a generic type without the generic argument specified
// is passed in.
if (input == null || input.FullName == null)
{
return new OpenApiSchema();
}
var key = GetKey(input);
// If the schema already exists in the References, simply return.
if (References.ContainsKey(key))
{
return new OpenApiSchema
{
Reference = new OpenApiReference
{
Id = key,
Type = ReferenceType.Schema
}
};
}
try
{
// There are multiple cases for input types that should be handled differently to match the OpenAPI spec.
//
// 1. Simple Type
// 2. Enum Type
// 3. Dictionary Type
// 4. Enumerable Type
// 5. Object Type
var schema = new OpenApiSchema();
if (input.IsSimple())
{
schema = input.MapToOpenApiSchema();
// Certain simple types yield more specific information.
if (input == typeof(char))
{
schema.MinLength = 1;
schema.MaxLength = 1;
}
else if (input == typeof(Guid))
{
schema.Example = new OpenApiString(Guid.Empty.ToString());
}
return schema;
}
if (input == typeof(Stream) || input.BaseType == typeof(Stream))
{
schema.Type = "string";
schema.Format = "binary";
return schema;
}
if (input.IsEnum)
{
schema.Type = "string";
foreach (var name in Enum.GetNames(input))
{
schema.Enum.Add(new OpenApiString(name));
}
return schema;
}
if (input.IsDictionary())
{
schema.Type = "object";
schema.AdditionalProperties = FindOrAddReference(input.GetGenericArguments()[1]);
return schema;
}
if (input.IsEnumerable())
{
schema.Type = "array";
schema.Items = FindOrAddReference(input.GetEnumerableItemType());
return schema;
}
var nullableUnderlyingType = Nullable.GetUnderlyingType(input);
if (nullableUnderlyingType?.IsEnum == true)
{
schema.Type = "string";
schema.Nullable = true;
foreach (var name in nullableUnderlyingType.GetEnumNames())
{
schema.Enum.Add(new OpenApiString(name));
}
return schema;
}
schema.Type = "object";
// Note this assignment is necessary to allow self-referencing type to finish
// without causing stack overflow.
// We can also assume that the schema is an object type at this point.
References[key] = schema;
var propertyNameDeclaringTypeMap = new Dictionary<string, Type>();
var typeAttributes = input.GetCustomAttributes(false);
foreach (var typeAttribute in typeAttributes)
{
if (typeAttribute.GetType().FullName == "Newtonsoft.Json.JsonObjectAttribute")
{
var type = typeAttribute.GetType();
var namingStrategyInfo = type.GetProperty("NamingStrategyType");
if (namingStrategyInfo != null)
{
var namingStrategyValue = namingStrategyInfo.GetValue(typeAttribute, null);
if (namingStrategyValue?.ToString()
== "Newtonsoft.Json.Serialization.CamelCaseNamingStrategy")
{
_propertyNameResolver = new CamelCasePropertyNameResolver();
}
}
}
}
var a = input.FullName;
PropertyInfo[] propertyInfos;
if (_schemaGenerationSettings.IncludeInheritanceInformation)
{
propertyInfos = input.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
if (input.BaseType != typeof(object))
{
var baseClassSchema = FindOrAddReference(input.BaseType);
schema.AllOf.Add(baseClassSchema);
}
if (_schemaGenerationSettings.DiscriminatorResolver != null)
{
var xmlIncludeAttributes = input.GetCustomAttributes<XmlIncludeAttribute>(false).ToArray();
if (xmlIncludeAttributes.Length > 0)
{
var discriminatorProperty = _schemaGenerationSettings.DiscriminatorResolver.ResolveProperty(input);
if (discriminatorProperty != null)
{
var openApiDiscriminator = new OpenApiDiscriminator()
{
PropertyName = discriminatorProperty.Name,
Mapping = new Dictionary<string, string>()
};
schema.Discriminator = openApiDiscriminator;
foreach (var xmlIncludeAttribute in xmlIncludeAttributes)
{
var childSchema = FindOrAddReference(xmlIncludeAttribute.Type);
schema.OneOf.Add(childSchema);
var mappingKey = _schemaGenerationSettings.DiscriminatorResolver.ResolveMappingKey(discriminatorProperty, xmlIncludeAttribute.Type);
openApiDiscriminator.Mapping[mappingKey] = childSchema.Reference.ReferenceV3;
}
}
}
}
}
else
{
propertyInfos = input.GetProperties();
}
foreach (var propertyInfo in propertyInfos)
{
var ignoreProperty = false;
var innerSchema = FindOrAddReference(propertyInfo.PropertyType);
var propertyName = _propertyNameResolver.ResolvePropertyName(propertyInfo);
// Construct property name like it shows up in documentation xml.
var propertyFullName = propertyInfo.DeclaringType.Namespace + "." +
propertyInfo.DeclaringType?.Name + "." + propertyInfo.Name;
if ( this._propertyDescriptionMap.ContainsKey( propertyFullName ) )
{
innerSchema.Description = this._propertyDescriptionMap[propertyFullName];
}
var attributes = propertyInfo.GetCustomAttributes(false);
foreach (var attribute in attributes)
{
if (attribute.GetType().FullName == "Newtonsoft.Json.JsonPropertyAttribute")
{
var type = attribute.GetType();
var requiredPropertyInfo = type.GetProperty("Required");
if (requiredPropertyInfo != null)
{
var requiredValue = Enum.GetName(
requiredPropertyInfo.PropertyType,
requiredPropertyInfo.GetValue(attribute, null));
if (requiredValue == "Always")
{
schema.Required.Add(propertyName);
}
}
}
if (attribute.GetType().FullName == "Newtonsoft.Json.JsonIgnoreAttribute")
{
ignoreProperty = true;
}
}
if (ignoreProperty)
{
continue;
}
var propertyDeclaringType = propertyInfo.DeclaringType;
if (propertyNameDeclaringTypeMap.ContainsKey(propertyName))
{
var existingPropertyDeclaringType = propertyNameDeclaringTypeMap[propertyName];
var duplicateProperty = true;
if (existingPropertyDeclaringType != null && propertyDeclaringType != null)
{
if (propertyDeclaringType.IsSubclassOf(existingPropertyDeclaringType)
|| (existingPropertyDeclaringType.IsInterface
&& propertyDeclaringType.ImplementInterface(existingPropertyDeclaringType)))
{
// Current property is on a derived class and hides the existing
schema.Properties[propertyName] = innerSchema;
duplicateProperty = false;
}
if (existingPropertyDeclaringType.IsSubclassOf(propertyDeclaringType)
|| (propertyDeclaringType.IsInterface
&& existingPropertyDeclaringType.ImplementInterface(propertyDeclaringType)))
{
// current property is hidden by the existing so don't add it
continue;
}
}
if (duplicateProperty)
{
throw new AddingSchemaReferenceFailedException(
key,
string.Format(
SpecificationGenerationMessages.DuplicateProperty,
propertyName,
input));
}
}
schema.Properties[propertyName] = innerSchema;
propertyNameDeclaringTypeMap.Add(propertyName, propertyDeclaringType);
}
References[key] = schema;
return new OpenApiSchema
{
Reference = new OpenApiReference
{
Id = key,
Type = ReferenceType.Schema
}
};
}
catch (Exception e)
{
// Something went wrong while fetching schema, so remove the key if exists from the references.
if (References.ContainsKey(key))
{
References.Remove(key);
}
throw new AddingSchemaReferenceFailedException(key, e.Message);
}
}
/// <summary>
/// Gets the key from the input object to use as reference string.
/// </summary>
/// <remarks>
/// This must match the regular expression ^[a-zA-Z0-9\.\-_]+$ due to OpenAPI V3 spec.
/// </remarks>
internal override string GetKey(Type input)
{
return _schemaGenerationSettings.SchemaIdResolver.ResolveSchemaId(input);
}
}
}