/
OpenIddictParameter.cs
1307 lines (1068 loc) · 55.1 KB
/
OpenIddictParameter.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Collections.Immutable;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text.Json;
#if SUPPORTS_JSON_NODES
using System.Text.Json.Nodes;
#endif
namespace OpenIddict.Abstractions;
/// <summary>
/// Represents an OpenIddict parameter value, that can be either a primitive value,
/// an array of strings or a complex JSON representation containing child nodes.
/// </summary>
public readonly struct OpenIddictParameter : IEquatable<OpenIddictParameter>
{
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(bool value) => Value = value;
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(bool? value) => Value = value;
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(JsonElement value) => Value = value;
#if SUPPORTS_JSON_NODES
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(JsonNode? value) => Value = value;
#endif
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(long value) => Value = value;
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(long? value) => Value = value;
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(string? value) => Value = value;
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(string?[]? value) => Value = value;
/// <summary>
/// Gets the child item corresponding to the specified index.
/// </summary>
/// <param name="index">The index of the child item.</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance containing the item value.</returns>
public OpenIddictParameter? this[int index] => GetUnnamedParameter(index);
/// <summary>
/// Gets the child item corresponding to the specified name.
/// </summary>
/// <param name="name">The name of the child item.</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance containing the item value.</returns>
public OpenIddictParameter? this[string name] => GetNamedParameter(name);
/// <summary>
/// Gets the number of named or unnamed child items contained in the current parameter or 0
/// if the parameter doesn't represent an array of strings, a JSON array or a JSON object.
/// </summary>
public int Count
{
get
{
return Value switch
{
// If the parameter is a primitive array of strings, return its length.
string?[] value => value.Length,
// If the parameter is a JSON array or a JSON object, return its length.
JsonElement { ValueKind: JsonValueKind.Array or JsonValueKind.Object } element
=> Count(element),
#if SUPPORTS_JSON_NODES
// If the parameter is a JsonArray, return its length.
JsonArray value => value.Count,
// If the parameter is a JsonObject, return its length.
JsonObject value => value.Count,
// If the parameter is a JsonValue wrapping a JsonElement,
// apply the same logic as with direct JsonElement instances.
JsonValue value when value.TryGetValue(out JsonElement element)
=> element.ValueKind is JsonValueKind.Array or JsonValueKind.Object ? Count(element) : 0,
// If the parameter is a JsonValue wrapping a well-known primitive type
// (e.g int or string), always return 0 as these types can't have a length.
JsonValue value when value.TryGetValue(out bool _) ||
value.TryGetValue(out int _) ||
value.TryGetValue(out long _) ||
value.TryGetValue(out string? _) => 0,
// If the parameter is any other JsonNode (e.g a JsonValue), serialize it
// to a JsonElement first to determine its actual JSON representation
// and extract the number of items if the element is a JSON array or object.
JsonNode value when JsonSerializer.SerializeToElement(value)
is JsonElement { ValueKind: JsonValueKind.Array or JsonValueKind.Object } element
=> Count(element),
#endif
// Otherwise, return 0.
_ => 0
};
static int Count(JsonElement element)
{
switch (element.ValueKind)
{
case JsonValueKind.Array:
return element.GetArrayLength();
case JsonValueKind.Object:
var count = 0;
using (var enumerator = element.EnumerateObject())
{
checked
{
while (enumerator.MoveNext())
{
count++;
}
}
}
return count;
default: return 0;
}
}
}
}
/// <summary>
/// Gets the associated value, that can be either a primitive CLR type
/// (e.g bool, string, long), an array of strings or a complex JSON object.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public object? Value { get; }
/// <summary>
/// Determines whether the current <see cref="OpenIddictParameter"/>
/// instance is equal to the specified <see cref="OpenIddictParameter"/>.
/// </summary>
/// <param name="other">The other object to which to compare this instance.</param>
/// <returns>
/// <see langword="true"/> if the two instances have both the same representation
/// (e.g <see cref="string"/>) and value, <see langword="false"/> otherwise.
/// </returns>
public bool Equals(OpenIddictParameter other)
{
return (left: Value, right: other.Value) switch
{
// If the two parameters reference the same instance, return true.
//
// Note: true will also be returned if the two parameters are null.
var (left, right) when ReferenceEquals(left, right) => true,
// If one of the two parameters is null, return false.
(null, _) or (_, null) => false,
// If the two parameters are booleans, compare them directly.
(bool left, bool right) => left == right,
// If the two parameters are integers, compare them directly.
(long left, long right) => left == right,
// If the two parameters are strings, use string.Equals().
(string left, string right) => string.Equals(left, right, StringComparison.Ordinal),
// If the two parameters are string arrays, use SequenceEqual().
(string?[] left, string?[] right) => left.SequenceEqual(right),
// If one of the two parameters is an undefined JsonElement, treat it
// as a null value and return true if the other parameter is null too.
(JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined }, var right)
=> right is null,
(var left, JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined })
=> left is null,
// If the two parameters are JsonElement instances, use the custom comparer.
(JsonElement left, JsonElement right) => DeepEquals(left, right),
// When one of the parameters is a JsonElement, compare their underlying values.
(JsonElement { ValueKind: JsonValueKind.True }, bool right) => right,
(bool left, JsonElement { ValueKind: JsonValueKind.True }) => left,
(JsonElement { ValueKind: JsonValueKind.False }, bool right) => !right,
(bool left, JsonElement { ValueKind: JsonValueKind.False }) => !left,
(JsonElement { ValueKind: JsonValueKind.Number } left, long right)
when left.TryGetInt64(out var result) => result == right,
(long left, JsonElement { ValueKind: JsonValueKind.Number } right)
when right.TryGetInt64(out var result) => left == result,
(JsonElement { ValueKind: JsonValueKind.String } left, string right)
=> string.Equals(left.GetString(), right, StringComparison.Ordinal),
(string left, JsonElement { ValueKind: JsonValueKind.String } right)
=> string.Equals(left, right.GetString(), StringComparison.Ordinal),
#if SUPPORTS_JSON_NODES
// When one of the parameters is a JsonValue, try to compare their underlying values
// if the wrapped type is a common CLR primitive type to avoid the less efficient
// JsonElement-based comparison, that requires doing a full JSON serialization.
(JsonValue left, bool right) when left.TryGetValue(out bool result) => result == right,
(bool left, JsonValue right) when right.TryGetValue(out bool result) => result == left,
(JsonValue left, long right) when left.TryGetValue(out int result) => result == right,
(long left, JsonValue right) when right.TryGetValue(out int result) => result == left,
(JsonValue left, long right) when left.TryGetValue(out long result) => result == right,
(long left, JsonValue right) when right.TryGetValue(out long result) => result == left,
(JsonValue left, string right) when left.TryGetValue(out string? result)
=> string.Equals(result, right, StringComparison.Ordinal),
(string left, JsonValue right) when right.TryGetValue(out string? result)
=> string.Equals(left, result, StringComparison.Ordinal),
#endif
// Otherwise, serialize both values to JsonElement and compare them.
#if SUPPORTS_DIRECT_JSON_ELEMENT_SERIALIZATION
var (left, right) => DeepEquals(
JsonSerializer.SerializeToElement(left, left.GetType()),
JsonSerializer.SerializeToElement(right, right.GetType()))
#else
var (left, right) => DeepEquals(
JsonSerializer.Deserialize<JsonElement>(JsonSerializer.Serialize(left, left.GetType())),
JsonSerializer.Deserialize<JsonElement>(JsonSerializer.Serialize(right, right.GetType())))
#endif
};
static bool DeepEquals(JsonElement left, JsonElement right)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
switch ((left.ValueKind, right.ValueKind))
{
case (JsonValueKind.Undefined, JsonValueKind.Undefined):
case (JsonValueKind.Null, JsonValueKind.Null):
case (JsonValueKind.False, JsonValueKind.False):
case (JsonValueKind.True, JsonValueKind.True):
return true;
// Treat undefined JsonElement instances as null values.
case (JsonValueKind.Undefined, JsonValueKind.Null):
case (JsonValueKind.Null, JsonValueKind.Undefined):
return true;
case (JsonValueKind.Number, JsonValueKind.Number):
return string.Equals(left.GetRawText(), right.GetRawText(), StringComparison.Ordinal);
case (JsonValueKind.String, JsonValueKind.String):
return string.Equals(left.GetString(), right.GetString(), StringComparison.Ordinal);
case (JsonValueKind.Array, JsonValueKind.Array):
{
var length = left.GetArrayLength();
if (length != right.GetArrayLength())
{
return false;
}
for (var index = 0; index < length; index++)
{
if (!DeepEquals(left[index], right[index]))
{
return false;
}
}
return true;
}
case (JsonValueKind.Object, JsonValueKind.Object):
{
foreach (var property in left.EnumerateObject())
{
if (!right.TryGetProperty(property.Name, out JsonElement element) ||
property.Value.ValueKind != element.ValueKind)
{
return false;
}
if (!DeepEquals(property.Value, element))
{
return false;
}
}
return true;
}
default: return false;
}
}
}
/// <summary>
/// Determines whether the current <see cref="OpenIddictParameter"/>
/// instance is equal to the specified <see cref="object"/>.
/// </summary>
/// <param name="obj">The other object to which to compare this instance.</param>
/// <returns>
/// <see langword="true"/> if the two instances have both the same representation
/// (e.g <see cref="string"/>) and value, <see langword="false"/> otherwise.
/// </returns>
public override bool Equals(object? obj) => obj is OpenIddictParameter parameter && Equals(parameter);
/// <summary>
/// Returns the hash code of the current <see cref="OpenIddictParameter"/> instance.
/// </summary>
/// <returns>The hash code for the current instance.</returns>
public override int GetHashCode()
{
return Value switch
{
// When the parameter value is null, return 0.
null => 0,
// When the parameter is an array of strings, compute the hash code of its items to
// match the logic used when treating a JsonElement instance representing an array.
string?[] value => GetHashCodeFromArray(value),
// When the parameter is a JsonElement, compute its hash code.
JsonElement value => GetHashCodeFromJsonElement(value),
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonValue wrapping a JsonElement,
// apply the same logic as with direct JsonElement instances.
JsonValue value when value.TryGetValue(out JsonElement element)
=> GetHashCodeFromJsonElement(element),
// When the parameter is a JsonValue, compute the hash code of its underlying value
// if the wrapped type is a common CLR primitive type to avoid the less efficient
// JsonElement-based computation, that requires doing a full JSON serialization.
JsonValue value when value.TryGetValue(out bool result) => result.GetHashCode(),
JsonValue value when value.TryGetValue(out int result) => result.GetHashCode(),
JsonValue value when value.TryGetValue(out long result) => result.GetHashCode(),
JsonValue value when value.TryGetValue(out string? result) => result.GetHashCode(),
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element
=> GetHashCodeFromJsonElement(element),
#endif
// Otherwise, use the default hash code method.
var value => value.GetHashCode()
};
static int GetHashCodeFromArray(string?[] array)
{
var hash = new HashCode();
for (var index = 0; index < array.Length; index++)
{
hash.Add(array[index]);
}
return hash.ToHashCode();
}
static int GetHashCodeFromJsonElement(JsonElement element)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
switch (element.ValueKind)
{
case JsonValueKind.Undefined:
case JsonValueKind.Null:
return 0;
case JsonValueKind.True:
return true.GetHashCode();
case JsonValueKind.False:
return false.GetHashCode();
case JsonValueKind.Number when element.TryGetInt64(out var result):
return result.GetHashCode();
case JsonValueKind.Number:
return element.GetRawText().GetHashCode();
case JsonValueKind.String:
return element.GetString()!.GetHashCode();
case JsonValueKind.Array:
{
var hash = new HashCode();
foreach (var item in element.EnumerateArray())
{
hash.Add(GetHashCodeFromJsonElement(item));
}
return hash.ToHashCode();
}
case JsonValueKind.Object:
{
var hash = new HashCode();
foreach (var property in element.EnumerateObject())
{
hash.Add(property.Name);
hash.Add(GetHashCodeFromJsonElement(property.Value));
}
return hash.ToHashCode();
}
default: return 0;
}
}
}
/// <summary>
/// Gets the child item corresponding to the specified name.
/// </summary>
/// <param name="name">The name of the child item.</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance containing the item value.</returns>
public OpenIddictParameter? GetNamedParameter(string name)
=> TryGetNamedParameter(name, out var value) ? value : (OpenIddictParameter?) null;
/// <summary>
/// Gets the child item corresponding to the specified index.
/// </summary>
/// <param name="index">The index of the child item.</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance containing the item value.</returns>
public OpenIddictParameter? GetUnnamedParameter(int index)
=> TryGetUnnamedParameter(index, out var value) ? value : (OpenIddictParameter?) null;
/// <summary>
/// Gets the named child items associated with the current parameter, if it represents a JSON object.
/// Note: if the JSON object contains multiple parameters with the same name, only the last occurrence is returned.
/// </summary>
/// <returns>A dictionary of all the parameters associated with the current instance.</returns>
public IReadOnlyDictionary<string, OpenIddictParameter> GetNamedParameters()
{
return Value switch
{
// When the parameter is a JsonElement representing an object, return the requested item.
JsonElement { ValueKind: JsonValueKind.Object } value => GetParametersFromJsonElement(value),
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonObject, return the requested item.
JsonObject value => GetParametersFromJsonNode(value),
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode value when JsonSerializer.SerializeToElement(value)
is JsonElement { ValueKind: JsonValueKind.Object } element
=> GetParametersFromJsonElement(element),
#endif
_ => ImmutableDictionary.Create<string, OpenIddictParameter>(StringComparer.Ordinal)
};
static IReadOnlyDictionary<string, OpenIddictParameter> GetParametersFromJsonElement(JsonElement element)
{
var parameters = new Dictionary<string, OpenIddictParameter>(StringComparer.Ordinal);
foreach (var property in element.EnumerateObject())
{
parameters[property.Name] = new(property.Value);
}
return parameters;
}
#if SUPPORTS_JSON_NODES
static IReadOnlyDictionary<string, OpenIddictParameter> GetParametersFromJsonNode(JsonObject node)
{
var parameters = new Dictionary<string, OpenIddictParameter>(node.Count, StringComparer.Ordinal);
foreach (var property in node)
{
parameters[property.Key] = new(property.Value);
}
return parameters;
}
#endif
}
/// <summary>
/// Gets the unnamed child items associated with the current parameter,
/// if it represents an array of strings or a JSON array.
/// </summary>
/// <returns>An enumeration of all the unnamed parameters associated with the current instance.</returns>
public IReadOnlyList<OpenIddictParameter> GetUnnamedParameters()
{
return Value switch
{
// When the parameter is an array of strings, return its items.
string?[] value => GetParametersFromArray(value),
// When the parameter is a JsonElement representing an array, return its children.
JsonElement { ValueKind: JsonValueKind.Array } value => GetParametersFromJsonElement(value),
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonArray, return its children.
JsonArray value => GetParametersFromJsonNode(value),
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode value when JsonSerializer.SerializeToElement(value)
is JsonElement { ValueKind: JsonValueKind.Array } element
=> GetParametersFromJsonElement(element),
#endif
_ => ImmutableList.Create<OpenIddictParameter>()
};
static IReadOnlyList<OpenIddictParameter> GetParametersFromArray(string?[] array)
{
var parameters = new OpenIddictParameter[array.Length];
for (var index = 0; index < array.Length; index++)
{
parameters[index] = new(array[index]);
}
return parameters;
}
static IReadOnlyList<OpenIddictParameter> GetParametersFromJsonElement(JsonElement element)
{
var length = element.GetArrayLength();
var parameters = new OpenIddictParameter[length];
for (var index = 0; index < length; index++)
{
parameters[index] = new(element[index]);
}
return parameters;
}
#if SUPPORTS_JSON_NODES
static IReadOnlyList<OpenIddictParameter> GetParametersFromJsonNode(JsonArray node)
{
var parameters = new OpenIddictParameter[node.Count];
for (var index = 0; index < node.Count; index++)
{
parameters[index] = new(node[index]);
}
return parameters;
}
#endif
}
/// <summary>
/// Returns the <see cref="string"/> representation of the current instance.
/// </summary>
/// <returns>The <see cref="string"/> representation associated with the parameter value.</returns>
public override string? ToString() => Value switch
{
null => string.Empty,
bool value => value ? bool.TrueString : bool.FalseString,
long value => value.ToString(CultureInfo.InvariantCulture),
string value => value,
string?[] value => string.Join(", ", value),
JsonElement value => value.ToString(),
#if SUPPORTS_JSON_NODES
JsonValue value when value.TryGetValue(out JsonElement element)
=> element.ToString(),
JsonValue value when value.TryGetValue(out bool result)
=> result ? bool.TrueString : bool.FalseString,
JsonValue value when value.TryGetValue(out int result)
=> result.ToString(CultureInfo.InvariantCulture),
JsonValue value when value.TryGetValue(out long result)
=> result.ToString(CultureInfo.InvariantCulture),
JsonValue value when value.TryGetValue(out string? result) => result,
JsonNode value => value.ToJsonString(),
#endif
_ => string.Empty
};
/// <summary>
/// Tries to get the child item corresponding to the specified name.
/// </summary>
/// <param name="name">The name of the child item.</param>
/// <param name="value">An <see cref="OpenIddictParameter"/> instance containing the item value.</param>
/// <returns><see langword="true"/> if the parameter could be found, <see langword="false"/> otherwise.</returns>
public bool TryGetNamedParameter(string name, out OpenIddictParameter value)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0192), nameof(name));
}
var result = Value switch
{
// When the parameter is a JsonElement representing an array, return the requested item.
JsonElement { ValueKind: JsonValueKind.Object } element =>
element.TryGetProperty(name, out JsonElement property) ? new(property) : null,
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonObject, return the requested item.
JsonObject node => node.TryGetPropertyValue(name, out JsonNode? property) ? new(property) : null,
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode node when JsonSerializer.SerializeToElement(node)
is JsonElement { ValueKind: JsonValueKind.Object } element
=> element.TryGetProperty(name, out JsonElement property) ? new(property) : null,
#endif
_ => (OpenIddictParameter?) null
};
value = result.GetValueOrDefault();
return result.HasValue;
}
/// <summary>
/// Tries to get the child item corresponding to the specified index.
/// </summary>
/// <param name="index">The index of the child item.</param>
/// <param name="value">An <see cref="OpenIddictParameter"/> instance containing the item value.</param>
/// <returns><see langword="true"/> if the parameter could be found, <see langword="false"/> otherwise.</returns>
public bool TryGetUnnamedParameter(int index, out OpenIddictParameter value)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.GetResourceString(SR.ID0193));
}
var result = Value switch
{
// When the parameter is an array of strings, return the requested item.
string?[] array => index < array.Length ? new(array[index]) : null,
// When the parameter is a JsonElement representing an array, return the requested item.
JsonElement { ValueKind: JsonValueKind.Array } element =>
index < element.GetArrayLength() ? new(element[index]) : null,
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonArray, return the requested item.
JsonArray node => index < node.Count ? new(node[index]) : null,
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode node when JsonSerializer.SerializeToElement(node)
is JsonElement { ValueKind: JsonValueKind.Array } element
=> index < element.GetArrayLength() ? new(element) : null,
#endif
_ => (OpenIddictParameter?) null
};
value = result.GetValueOrDefault();
return result.HasValue;
}
/// <summary>
/// Writes the parameter value to the specified JSON writer.
/// </summary>
/// <param name="writer">The UTF-8 JSON writer.</param>
public void WriteTo(Utf8JsonWriter writer)
{
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
switch (Value)
{
// Note: undefined JsonElement values are assimilated to null values.
case null:
case JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined }:
writer.WriteNullValue();
break;
case bool value:
writer.WriteBooleanValue(value);
break;
case long value:
writer.WriteNumberValue(value);
break;
case string value:
writer.WriteStringValue(value);
break;
case string?[] value:
writer.WriteStartArray();
for (var index = 0; index < value.Length; index++)
{
writer.WriteStringValue(value[index]);
}
writer.WriteEndArray();
break;
case JsonElement value:
value.WriteTo(writer);
break;
#if SUPPORTS_JSON_NODES
case JsonNode value:
value.WriteTo(writer);
break;
#endif
}
}
/// <summary>
/// Determines whether two <see cref="OpenIddictParameter"/> instances are equal.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns><see langword="true"/> if the two instances are equal, <see langword="false"/> otherwise.</returns>
public static bool operator ==(OpenIddictParameter left, OpenIddictParameter right) => left.Equals(right);
/// <summary>
/// Determines whether two <see cref="OpenIddictParameter"/> instances are not equal.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns><see langword="true"/> if the two instances are not equal, <see langword="false"/> otherwise.</returns>
public static bool operator !=(OpenIddictParameter left, OpenIddictParameter right) => !left.Equals(right);
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a boolean.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator bool(OpenIddictParameter? parameter)
=> ((bool?) parameter).GetValueOrDefault();
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a nullable boolean.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator bool?(OpenIddictParameter? parameter)
{
return parameter?.Value switch
{
// When the parameter is a null value or a JsonElement representing null, return null.
null or JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined } => null,
// When the parameter is a boolean value, return it as-is.
bool value => value,
// When the parameter is a string value, try to parse it.
string value => bool.TryParse(value, out var result) ? result : null,
// When the parameter is a JsonElement, try to convert it if it's of a supported type.
JsonElement value => ConvertFromJsonElement(value),
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonValue wrapping a JsonElement,
// apply the same logic as with direct JsonElement instances.
JsonValue value when value.TryGetValue(out JsonElement element) => ConvertFromJsonElement(element),
// When the parameter is a JsonValue wrapping a boolean, return it as-is.
JsonValue value when value.TryGetValue(out bool result) => result,
// When the parameter is a JsonValue wrapping a string, try to parse it.
JsonValue value when value.TryGetValue(out string? text) =>
bool.TryParse(text, out var result) ? result : null,
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element
=> ConvertFromJsonElement(element),
#endif
// If the parameter is of a different type, return null to indicate the conversion failed.
_ => null
};
static bool? ConvertFromJsonElement(JsonElement element) => element.ValueKind switch
{
// When the parameter is a JsonElement representing a boolean, return it as-is.
JsonValueKind.True => true,
JsonValueKind.False => false,
// When the parameter is a JsonElement representing a string, try to parse it.
JsonValueKind.String => bool.TryParse(element.GetString(), out var result) ? result : null,
_ => null
};
}
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a <see cref="JsonElement"/>.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator JsonElement(OpenIddictParameter? parameter)
{
return parameter?.Value switch
{
// When the parameter is a null value, return an undefined JsonElement.
null => default,
// When the parameter is already a JsonElement, return it as-is.
JsonElement value => value,
#if SUPPORTS_JSON_NODES
// When the parameter is JsonNode, serialize it as a JsonElement.
JsonNode value => JsonSerializer.SerializeToElement(value),
#endif
// When the parameter is a string starting with '{' or '[' (which would correspond
// to a JSON object or array), try to deserialize it to get a JsonElement instance.
string { Length: > 0 } value when value[0] is '{' or '[' =>
DeserializeElement(value) ??
DeserializeElement(JsonSerializer.Serialize(value)) ?? default,
// Otherwise, serialize it to get a JsonElement instance.
#if SUPPORTS_DIRECT_JSON_ELEMENT_SERIALIZATION
object value => JsonSerializer.SerializeToElement(value, value.GetType())
#else
object value => DeserializeElement(JsonSerializer.Serialize(value)) ?? default
#endif
};
static JsonElement? DeserializeElement(string value)
{
try
{
using var document = JsonDocument.Parse(value);
return document.RootElement.Clone();
}
catch (JsonException)
{
return null;
}
}
}
#if SUPPORTS_JSON_NODES
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a <see cref="JsonNode"/>.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator JsonNode?(OpenIddictParameter? parameter)
{
return parameter?.Value switch
{
// When the parameter is a null value or a JsonElement representing null, return null.
null or JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined } => null,
// When the parameter is already a JsonNode, return it as-is.
JsonNode value => value,
// When the parameter is a boolean, return a JsonValue.
bool value => JsonValue.Create(value),
// When the parameter is an integer, return a JsonValue.
long value => JsonValue.Create(value),
// When the parameter is a string starting with '{' or '[' (which would correspond
// to a JSON object or array), try to deserialize it to get a JsonNode instance.
string { Length: > 0 } value when value[0] is '{' or '[' => DeserializeNode(value),
// When the parameter is a string, return a JsonValue.
string value => JsonValue.Create(value),
// When the parameter is an array of strings, return a JsonArray.
string?[] value => CreateArray(value),
// When the parameter is JsonElement, deserialize it as a JsonNode.
JsonElement value => JsonSerializer.Deserialize<JsonNode>(value),
// If the parameter is of a different type, return null to indicate the conversion failed.
_ => null
};
static JsonNode? DeserializeNode(string value)
{
try
{
return JsonNode.Parse(value);
}
catch (JsonException)
{
return null;
}
}
static JsonArray? CreateArray(string?[] values)
{
var array = new JsonArray();
for (var index = 0; index < values.Length; index++)
{
array.Add(values[index]);
}
return array;
}
}
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a <see cref="JsonArray"/>.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator JsonArray?(OpenIddictParameter? parameter)
=> ((JsonNode?) parameter) as JsonArray;
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a <see cref="JsonObject"/>.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator JsonObject?(OpenIddictParameter? parameter)
=> ((JsonNode?) parameter) as JsonObject;
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a <see cref="JsonValue"/>.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator JsonValue?(OpenIddictParameter? parameter)
=> ((JsonNode?) parameter) as JsonValue;
#endif
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a long integer.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator long(OpenIddictParameter? parameter)
=> ((long?) parameter).GetValueOrDefault();
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a nullable long integer.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator long?(OpenIddictParameter? parameter)
{
return parameter?.Value switch
{
// When the parameter is a null value or a JsonElement representing null, return null.
null or JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined } => null,
// When the parameter is an integer, return it as-is.
long value => value,