Skip to content

Commit 46b2e1b

Browse files
committed
add
1 parent f3f71ee commit 46b2e1b

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

app/src/main/java/hexlet/code/MapSchema.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
public class MapSchema extends BaseSchema<MapSchema> {
66
private int requiredSize = -1;
7+
private Map<String, BaseSchema<?>> schemas;
78

89
@Override
910
public boolean isValid(Object value) {
@@ -20,11 +21,25 @@ public boolean isValid(Object value) {
2021
if (requiredSize != -1 && map.size() != requiredSize) {
2122
return false;
2223
}
24+
if (schemas != null) {
25+
for (Map.Entry<String, BaseSchema<?>> entry : schemas.entrySet()) {
26+
String key = entry.getKey();
27+
BaseSchema<?> schema = entry.getValue();
28+
if (!map.containsKey(key) || !schema.isValid(map.get(key))) {
29+
return false;
30+
}
31+
}
32+
}
2333
return true;
2434
}
2535

2636
public MapSchema sizeof(int size) {
2737
this.requiredSize = size;
2838
return this;
2939
}
40+
41+
public MapSchema shape(Map<String, BaseSchema<?>> shapeSchemas) {
42+
this.schemas = shapeSchemas;
43+
return this;
44+
}
3045
}

app/src/test/java/hexlet/code/MapSchemaTest.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,46 @@ public void testCombinedRules() {
6363
data.put("key2", "value2");
6464
assertTrue(schema.isValid(data));
6565
}
66+
67+
@Test
68+
public void testShape() {
69+
Validator v = new Validator();
70+
MapSchema schema = v.map();
71+
72+
Map<String, BaseSchema<?>> schemas = new HashMap<>();
73+
schemas.put("firstName", v.string().required());
74+
schemas.put("lastName", v.string().required().minLength(2));
75+
76+
schema.shape(schemas);
77+
78+
Map<String, String> human1 = new HashMap<>();
79+
human1.put("firstName", "John");
80+
human1.put("lastName", "Smith");
81+
assertTrue(schema.isValid(human1)); // true
82+
83+
Map<String, String> human2 = new HashMap<>();
84+
human2.put("firstName", "John");
85+
human2.put("lastName", null);
86+
assertFalse(schema.isValid(human2)); // false
87+
88+
Map<String, String> human3 = new HashMap<>();
89+
human3.put("firstName", "Anna");
90+
human3.put("lastName", "B");
91+
assertFalse(schema.isValid(human3)); // false
92+
93+
Map<String, String> human4 = new HashMap<>();
94+
human4.put("firstName", "Alice");
95+
human4.put("lastName", "Johnson");
96+
assertTrue(schema.isValid(human4)); // true
97+
98+
Map<String, String> human5 = new HashMap<>();
99+
human5.put("firstName", null);
100+
human5.put("lastName", "Doe");
101+
assertFalse(schema.isValid(human5)); // false
102+
103+
Map<String, String> human6 = new HashMap<>();
104+
human6.put("firstName", "Bob");
105+
human6.put("lastName", "");
106+
assertFalse(schema.isValid(human6)); // false
107+
}
66108
}

0 commit comments

Comments
 (0)