-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathStringOrStringList.cs
More file actions
61 lines (53 loc) · 2.29 KB
/
Copy pathStringOrStringList.cs
File metadata and controls
61 lines (53 loc) · 2.29 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
// Copyright (c) The LEGO Group. All rights reserved.
namespace LEGO.AsyncAPI.Bindings
{
using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using LEGO.AsyncAPI.Models;
using LEGO.AsyncAPI.Models.Interfaces;
using LEGO.AsyncAPI.Readers.ParseNodes;
public class StringOrStringList : IAsyncApiElement
{
public StringOrStringList(AsyncApiAny value)
{
this.Value = value.GetNode() switch
{
JsonArray array => IsValidStringList(array) ? new AsyncApiAny(array) : throw new ArgumentException($"{nameof(StringOrStringList)} value should only contain string items."),
JsonValue jValue => IsString(jValue) ? new AsyncApiAny(jValue) : throw new ArgumentException($"{nameof(StringOrStringList)} should be a string value or a string list."),
_ => throw new ArgumentException($"{nameof(StringOrStringList)} should be a string value or a string list."),
};
}
public AsyncApiAny Value { get; }
public static StringOrStringList Parse(ParseNode node)
{
switch (node)
{
case ValueNode:
return new StringOrStringList(new AsyncApiAny(node.GetScalarValue()));
case ListNode listNode:
{
var jsonArray = new JsonArray();
foreach (var item in listNode)
{
jsonArray.Add(item.GetScalarValue());
}
return new StringOrStringList(new AsyncApiAny(jsonArray));
}
default:
throw new ArgumentException($"An error occured while parsing a {nameof(StringOrStringList)} node. " +
$"Node should contain a string value or a list of strings.");
}
}
private static bool IsString(JsonNode value)
{
var element = JsonDocument.Parse(value.ToJsonString()).RootElement;
return element.ValueKind == JsonValueKind.String;
}
private static bool IsValidStringList(JsonArray array)
{
return array.All(x => IsString(x));
}
}
}