1 /*
2 * Copyright 2020-2022 Foreseeti AB <https://foreseeti.com>
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.mal_lang.langspec.builders.step;
18
19 import static java.util.Objects.requireNonNull;
20 import static org.mal_lang.langspec.Utils.requireIdentifier;
21
22 import jakarta.json.JsonObject;
23
24 /**
25 * A builder for creating {@link org.mal_lang.langspec.step.StepReference} objects.
26 *
27 * @since 1.0.0
28 */
29 public abstract class StepReferenceBuilder extends StepExpressionBuilder {
30 private final String name;
31
32 /**
33 * Constructs a new {@code StepReferenceBuilder} object.
34 *
35 * @param name the name of the reference step
36 * @throws java.lang.NullPointerException if {@code name} is {@code null}
37 * @throws java.lang.IllegalArgumentException if {@code name} is not a valid identifier
38 * @since 1.0.0
39 */
40 protected StepReferenceBuilder(String name) {
41 this.name = requireIdentifier(name);
42 }
43
44 /**
45 * Returns the name of this {@code StepReferenceBuilder} object.
46 *
47 * @return the name of this {@code StepReferenceBuilder} object
48 * @since 1.0.0
49 */
50 public String getName() {
51 return this.name;
52 }
53
54 /**
55 * Creates a new {@code StepReferenceBuilder} from a {@link jakarta.json.JsonObject}.
56 *
57 * @param jsonStepReference the {@link jakarta.json.JsonObject}
58 * @return a new {@code StepReferenceBuilder}
59 * @throws java.lang.NullPointerException if {@code jsonStepReference} is {@code null}
60 * @since 1.0.0
61 */
62 public static StepReferenceBuilder fromJson(JsonObject jsonStepReference) {
63 requireNonNull(jsonStepReference);
64 var name = jsonStepReference.getString("name");
65 switch (jsonStepReference.getString("type")) {
66 case "field":
67 return new StepFieldBuilder(name);
68 case "attackStep":
69 return new StepAttackStepBuilder(name);
70 case "variable":
71 return new StepVariableBuilder(name);
72 default:
73 throw new RuntimeException(
74 String.format(
75 "Invalid step expression type \"%s\"", jsonStepReference.getString("type")));
76 }
77 }
78 }