-
-
Notifications
You must be signed in to change notification settings - Fork 548
Expand file tree
/
Copy pathPropertyModel.cs
More file actions
382 lines (326 loc) · 15 KB
/
PropertyModel.cs
File metadata and controls
382 lines (326 loc) · 15 KB
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
378
379
380
381
382
//-----------------------------------------------------------------------
// <copyright file="PropertyModel.cs" company="NJsonSchema">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
using System.Globalization;
using System.Runtime.CompilerServices;
using NJsonSchema.CodeGeneration.Models;
namespace NJsonSchema.CodeGeneration.CSharp.Models
{
/// <summary>The CSharp property template model.</summary>
public class PropertyModel : PropertyModelBase
{
private static readonly HashSet<string?> RangeFormats =
[
JsonFormatStrings.Integer,
JsonFormatStrings.Float,
JsonFormatStrings.Double,
JsonFormatStrings.Long,
JsonFormatStrings.ULong,
JsonFormatStrings.Decimal
];
private readonly JsonSchemaProperty _property;
private readonly CSharpGeneratorSettings _settings;
private readonly CSharpTypeResolver _resolver;
/// <summary>Initializes a new instance of the <see cref="PropertyModel"/> class.</summary>
/// <param name="classTemplateModel">The class template model.</param>
/// <param name="property">The property.</param>
/// <param name="typeResolver">The type resolver.</param>
/// <param name="settings">The settings.</param>
public PropertyModel(
ClassTemplateModel classTemplateModel,
JsonSchemaProperty property,
CSharpTypeResolver typeResolver,
CSharpGeneratorSettings settings)
: base(property, classTemplateModel, typeResolver, settings)
{
_property = property;
_settings = settings;
_resolver = typeResolver;
}
/// <summary>Gets the name of the property.</summary>
public string Name => _property.Name;
/// <summary>Gets the type of the property.</summary>
public override string Type => _resolver.Resolve(_property, _property.IsNullable(_settings.SchemaType), GetTypeNameHint());
/// <summary>Gets a value indicating whether the property has a description.</summary>
public bool HasDescription => !string.IsNullOrEmpty(_property.Description);
/// <summary>Gets the description.</summary>
public string? Description => _property.Description;
/// <summary>Gets the name of the field.</summary>
public string FieldName => _settings.FieldNamePrefix + ConversionUtilities.ConvertToLowerCamelCase(PropertyName, true);
/// <summary>Gets a value indicating whether the property is nullable.</summary>
public override bool IsNullable => (_settings.GenerateOptionalPropertiesAsNullable && !_property.IsRequired) || base.IsNullable;
/// <summary>Gets or sets a value indicating whether empty strings are allowed.</summary>
public bool AllowEmptyStrings =>
_property.ActualTypeSchema.Type.IsString() &&
(_property.MinLength == null || _property.MinLength == 0);
/// <summary>Gets a value indicating whether this is an array property which cannot be null.</summary>
public bool HasSetter =>
!_property.ActualSchema.HasConstValue &&
(_property.IsNullable(_settings.SchemaType) || (!_property.ActualTypeSchema.IsArray || !_settings.GenerateImmutableArrayProperties) &&
(!_property.ActualTypeSchema.IsDictionary || !_settings.GenerateImmutableDictionaryProperties));
/// <summary>Gets the json property required.</summary>
public string JsonPropertyRequiredCode
{
get
{
if (_settings.RequiredPropertiesMustBeDefined && _property.IsRequired)
{
if (!IsNullable)
{
return "Newtonsoft.Json.Required.Always";
}
else
{
return "Newtonsoft.Json.Required.AllowNull";
}
}
else
{
if (!IsNullable)
{
return "Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore";
}
else
{
return "Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore";
}
}
}
}
/// <summary>Gets a value indicating whether to render a required attribute.</summary>
public bool RenderRequiredAttribute
{
get
{
if (!_settings.GenerateDataAnnotations || !_property.IsRequired || _property.IsNullable(_settings.SchemaType))
{
return false;
}
return _property.ActualTypeSchema.IsAnyType ||
_property.ActualTypeSchema.Type.IsObject() ||
_property.ActualTypeSchema.Type.IsString() ||
_property.ActualTypeSchema.Type.IsArray();
}
}
/// <summary>Gets a value indicating whether to render a range attribute.</summary>
public bool RenderRangeAttribute
{
get
{
if (!_settings.GenerateDataAnnotations)
{
return false;
}
if (!_property.ActualTypeSchema.Type.IsNumber() && !_property.ActualTypeSchema.Type.IsInteger())
{
return false;
}
return _property.ActualSchema.Maximum.HasValue || _property.ActualSchema.Minimum.HasValue;
}
}
private bool IsDecimalRange => GetSchemaFormat(_property.ActualSchema) is JsonFormatStrings.Decimal;
/// <summary>
/// The type of range attribute, used when the value is not double or integer.
/// </summary>
public string? RangeType => IsDecimalRange ? "decimal" : null;
/// <summary>Gets the minimum value of the range attribute.</summary>
public string RangeMinimumValue
{
get
{
var schema = _property.ActualSchema;
var propertyFormat = GetSchemaFormat(schema);
var format = GetRangeFormat(propertyFormat);
var type = GetRangeType(propertyFormat);
var minimum = schema.Minimum;
if (minimum.HasValue && schema.IsExclusiveMinimum)
{
if (propertyFormat is JsonFormatStrings.Integer or JsonFormatStrings.Long)
{
minimum++;
}
else if (schema.MultipleOf.HasValue)
{
minimum += schema.MultipleOf;
}
else
{
// TODO - add support for doubles, singles and decimals here
}
}
if (IsDecimalRange)
{
// special case decimals
return ValueGeneratorBase.ConvertToNumberToStringCore(minimum.GetValueOrDefault(decimal.MinValue));
}
return minimum.HasValue
? ValueGenerator.GetNumericValue(schema.Type, EnsureBounds(propertyFormat, minimum.Value), format)
: type + "." + nameof(double.MinValue);
}
}
/// <summary>Gets the maximum value of the range attribute.</summary>
public string RangeMaximumValue
{
get
{
var schema = _property.ActualSchema;
var propertyFormat = GetSchemaFormat(schema);
var format = GetRangeFormat(propertyFormat);
var type = GetRangeType(propertyFormat);
var maximum = schema.Maximum;
if (maximum.HasValue && schema.IsExclusiveMaximum)
{
if (propertyFormat is JsonFormatStrings.Integer or JsonFormatStrings.Long)
{
maximum--;
}
else if (schema.MultipleOf.HasValue)
{
maximum -= schema.MultipleOf;
}
else
{
// TODO - add support for doubles, singles and decimals here
}
}
if (IsDecimalRange)
{
// special case decimals
return ValueGeneratorBase.ConvertToNumberToStringCore(maximum.GetValueOrDefault(decimal.MaxValue));
}
return maximum.HasValue
? ValueGenerator.GetNumericValue(schema.Type, EnsureBounds(propertyFormat, maximum.Value), format)
: type + "." + nameof(double.MaxValue);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static decimal EnsureBounds(string? propertyFormat, decimal value)
{
return propertyFormat switch
{
JsonFormatStrings.Integer => Clamp(value, int.MinValue, int.MaxValue),
JsonFormatStrings.Long => Clamp(value, long.MinValue, long.MaxValue),
JsonFormatStrings.ULong => Clamp(value, ulong.MinValue, ulong.MaxValue),
_ => value,
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static decimal Clamp(decimal value, decimal min, decimal max)
{
if (value < min)
{
return min;
}
return value > max ? max : value;
}
/// <summary>Gets a value indicating whether to render a string length attribute.</summary>
public bool RenderStringLengthAttribute
{
get
{
if (!_settings.GenerateDataAnnotations)
{
return false;
}
if (_property.IsRequired && _property.MinLength == 1 && _property.MaxLength == null)
{
return false; // handled by RequiredAttribute
}
return _property.ActualTypeSchema.Type.IsString() &&
(_property.ActualSchema.MinLength.HasValue || _property.ActualSchema.MaxLength.HasValue);
}
}
/// <summary>Gets the minimum value of the string length attribute.</summary>
public int StringLengthMinimumValue => _property.ActualSchema.MinLength ?? 0;
/// <summary>Gets the maximum value of the string length attribute.</summary>
public string StringLengthMaximumValue => _property.ActualSchema.MaxLength.HasValue ? _property.ActualSchema.MaxLength.Value.ToString(CultureInfo.InvariantCulture) : $"int.{nameof(int.MaxValue)}";
/// <summary>Gets a value indicating whether to render the min length attribute.</summary>
public bool RenderMinLengthAttribute
{
get
{
if (!_settings.GenerateDataAnnotations)
{
return false;
}
return _property.ActualTypeSchema.Type.IsArray() && _property.ActualSchema.MinItems > 0;
}
}
/// <summary>Gets the value of the min length attribute.</summary>
public int MinLengthAttribute => _property.ActualSchema.MinItems;
/// <summary>Gets a value indicating whether to render the max length attribute.</summary>
public bool RenderMaxLengthAttribute
{
get
{
if (!_settings.GenerateDataAnnotations)
{
return false;
}
return _property.ActualTypeSchema.Type.IsArray() && _property.ActualSchema.MaxItems > 0;
}
}
/// <summary>Gets the value of the max length attribute.</summary>
public int MaxLengthAttribute => _property.ActualSchema.MaxItems;
/// <summary>Gets a value indicating whether to render a regular expression attribute.</summary>
public bool RenderRegularExpressionAttribute
{
get
{
if (!_settings.GenerateDataAnnotations)
{
return false;
}
return _property.ActualTypeSchema.Type.IsString() &&
!string.IsNullOrEmpty(_property.ActualSchema.Pattern);
}
}
/// <summary>Gets the regular expression value for the regular expression attribute.</summary>
public string? RegularExpressionValue => _property.ActualSchema.Pattern?.Replace("\"", "\"\"");
/// <summary>Gets a value indicating whether the property type is string enum.</summary>
public bool IsStringEnum => _property.ActualTypeSchema.IsEnumeration && _property.ActualTypeSchema.Type.IsString();
/// <summary>Gets a value indicating whether the property should be formatted like a date.</summary>
public bool IsDate => _property.ActualSchema.Format == JsonFormatStrings.Date;
/// <summary>Gets a value indicating whether the property is deprecated.</summary>
public bool IsDeprecated => _property.IsDeprecated;
/// <summary>Gets a value indicating whether the property has a deprecated message.</summary>
public bool HasDeprecatedMessage => !string.IsNullOrEmpty(_property.DeprecatedMessage);
/// <summary>Gets the deprecated message.</summary>
public string? DeprecatedMessage => _property.DeprecatedMessage;
private string? GetSchemaFormat(JsonSchema schema)
{
if (Type is "long" or "long?")
{
return JsonFormatStrings.Long;
}
if (schema.Format == null)
{
switch (schema.Type)
{
case JsonObjectType.Integer:
return JsonFormatStrings.Integer;
case JsonObjectType.Number:
return JsonFormatStrings.Double;
}
}
return schema.Format;
}
private static string GetRangeFormat(string? propertyFormat) =>
RangeFormats.Contains(propertyFormat) ? propertyFormat! : JsonFormatStrings.Double;
private static string GetRangeType(string? propertyFormat) =>
propertyFormat switch
{
JsonFormatStrings.Integer => "int",
JsonFormatStrings.Float => "float",
JsonFormatStrings.Double => "double",
JsonFormatStrings.Long => "long",
JsonFormatStrings.ULong => "ulong",
JsonFormatStrings.Decimal => "decimal",
_ => "double",
};
}
}