JsonValidator.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. /*
  2. * JsonValidator.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "JsonValidator.h"
  12. #include "JsonUtils.h"
  13. #include "../VCMI_Lib.h"
  14. #include "../filesystem/Filesystem.h"
  15. #include "../modding/ModScope.h"
  16. #include "../modding/CModHandler.h"
  17. #include "../ScopeGuard.h"
  18. VCMI_LIB_NAMESPACE_BEGIN
  19. // Algorithm for detection of typos in words
  20. // Determines how 'different' two strings are - how many changes must be done to turn one string into another one
  21. // https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows
  22. static int getLevenshteinDistance(const std::string & s, const std::string & t)
  23. {
  24. int n = t.size();
  25. int m = s.size();
  26. // create two work vectors of integer distances
  27. std::vector<int> v0(n+1, 0);
  28. std::vector<int> v1(n+1, 0);
  29. // initialize v0 (the previous row of distances)
  30. // this row is A[0][i]: edit distance from an empty s to t;
  31. // that distance is the number of characters to append to s to make t.
  32. for (int i = 0; i < n; ++i)
  33. v0[i] = i;
  34. for (int i = 0; i < m; ++i)
  35. {
  36. // calculate v1 (current row distances) from the previous row v0
  37. // first element of v1 is A[i + 1][0]
  38. // edit distance is delete (i + 1) chars from s to match empty t
  39. v1[0] = i + 1;
  40. // use formula to fill in the rest of the row
  41. for (int j = 0; j < n; ++j)
  42. {
  43. // calculating costs for A[i + 1][j + 1]
  44. int deletionCost = v0[j + 1] + 1;
  45. int insertionCost = v1[j] + 1;
  46. int substitutionCost;
  47. if (s[i] == t[j])
  48. substitutionCost = v0[j];
  49. else
  50. substitutionCost = v0[j] + 1;
  51. v1[j + 1] = std::min({deletionCost, insertionCost, substitutionCost});
  52. }
  53. // copy v1 (current row) to v0 (previous row) for next iteration
  54. // since data in v1 is always invalidated, a swap without copy could be more efficient
  55. std::swap(v0, v1);
  56. }
  57. // after the last swap, the results of v1 are now in v0
  58. return v0[n];
  59. }
  60. /// Searches for keys similar to 'target' in 'candidates' map
  61. /// Returns closest match or empty string if no suitable candidates are found
  62. static std::string findClosestMatch(JsonMap candidates, std::string target)
  63. {
  64. // Maximum distance at which we can consider strings to be similar
  65. // If strings have more different symbols than this number then it is not a typo, but a completely different word
  66. static constexpr int maxDistance = 5;
  67. int bestDistance = maxDistance;
  68. std::string bestMatch;
  69. for (auto const & candidate : candidates)
  70. {
  71. int newDistance = getLevenshteinDistance(candidate.first, target);
  72. if (newDistance < bestDistance)
  73. {
  74. bestDistance = newDistance;
  75. bestMatch = candidate.first;
  76. }
  77. }
  78. return bestMatch;
  79. }
  80. static std::string emptyCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  81. {
  82. // check is not needed - e.g. incorporated into another check
  83. return "";
  84. }
  85. static std::string notImplementedCheck(JsonValidator & validator,
  86. const JsonNode & baseSchema,
  87. const JsonNode & schema,
  88. const JsonNode & data)
  89. {
  90. return "Not implemented entry in schema";
  91. }
  92. static std::string schemaListCheck(JsonValidator & validator,
  93. const JsonNode & baseSchema,
  94. const JsonNode & schema,
  95. const JsonNode & data,
  96. const std::string & errorMsg,
  97. const std::function<bool(size_t)> & isValid)
  98. {
  99. std::string errors = "<tested schemas>\n";
  100. size_t result = 0;
  101. for(const auto & schemaEntry : schema.Vector())
  102. {
  103. std::string error = validator.check(schemaEntry, data);
  104. if (error.empty())
  105. {
  106. result++;
  107. }
  108. else
  109. {
  110. errors += error;
  111. errors += "<end of schema>\n";
  112. }
  113. }
  114. if (isValid(result))
  115. return "";
  116. else
  117. return validator.makeErrorMessage(errorMsg) + errors;
  118. }
  119. static std::string allOfCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  120. {
  121. return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass all schemas", [&schema](size_t count)
  122. {
  123. return count == schema.Vector().size();
  124. });
  125. }
  126. static std::string anyOfCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  127. {
  128. return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass any schema", [](size_t count)
  129. {
  130. return count > 0;
  131. });
  132. }
  133. static std::string oneOfCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  134. {
  135. return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass exactly one schema", [](size_t count)
  136. {
  137. return count == 1;
  138. });
  139. }
  140. static std::string notCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  141. {
  142. if (validator.check(schema, data).empty())
  143. return validator.makeErrorMessage("Successful validation against negative check");
  144. return "";
  145. }
  146. static std::string enumCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  147. {
  148. for(const auto & enumEntry : schema.Vector())
  149. {
  150. if (data == enumEntry)
  151. return "";
  152. }
  153. std::string errorMessage = "Key must have one of predefined values:" + schema.toCompactString();
  154. return validator.makeErrorMessage(errorMessage);
  155. }
  156. static std::string constCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  157. {
  158. if (data == schema)
  159. return "";
  160. return validator.makeErrorMessage("Key must have have constant value");
  161. }
  162. static std::string typeCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  163. {
  164. static const std::unordered_map<std::string, JsonNode::JsonType> stringToType =
  165. {
  166. {"null", JsonNode::JsonType::DATA_NULL},
  167. {"boolean", JsonNode::JsonType::DATA_BOOL},
  168. {"number", JsonNode::JsonType::DATA_FLOAT},
  169. {"integer", JsonNode::JsonType::DATA_INTEGER},
  170. {"string", JsonNode::JsonType::DATA_STRING},
  171. {"array", JsonNode::JsonType::DATA_VECTOR},
  172. {"object", JsonNode::JsonType::DATA_STRUCT}
  173. };
  174. const auto & typeName = schema.String();
  175. auto it = stringToType.find(typeName);
  176. if(it == stringToType.end())
  177. {
  178. return validator.makeErrorMessage("Unknown type in schema:" + typeName);
  179. }
  180. JsonNode::JsonType type = it->second;
  181. // for "number" type both float and integer are allowed
  182. if(type == JsonNode::JsonType::DATA_FLOAT && data.isNumber())
  183. return "";
  184. if(type != data.getType() && data.getType() != JsonNode::JsonType::DATA_NULL)
  185. return validator.makeErrorMessage("Type mismatch! Expected " + schema.String());
  186. return "";
  187. }
  188. static std::string refCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  189. {
  190. std::string URI = schema.String();
  191. //node must be validated using schema pointed by this reference and not by data here
  192. //Local reference. Turn it into more easy to handle remote ref
  193. if (boost::algorithm::starts_with(URI, "#"))
  194. {
  195. const std::string name = validator.usedSchemas.back();
  196. const std::string nameClean = name.substr(0, name.find('#'));
  197. URI = nameClean + URI;
  198. }
  199. return validator.check(URI, data);
  200. }
  201. static std::string formatCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  202. {
  203. auto formats = validator.getKnownFormats();
  204. std::string errors;
  205. auto checker = formats.find(schema.String());
  206. if (checker != formats.end())
  207. {
  208. if (data.isString())
  209. {
  210. std::string result = checker->second(data);
  211. if (!result.empty())
  212. errors += validator.makeErrorMessage(result);
  213. }
  214. else
  215. {
  216. errors += validator.makeErrorMessage("Format value must be string: " + schema.String());
  217. }
  218. }
  219. else
  220. errors += validator.makeErrorMessage("Unsupported format type: " + schema.String());
  221. return errors;
  222. }
  223. static std::string maxLengthCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  224. {
  225. if (data.String().size() > schema.Float())
  226. return validator.makeErrorMessage((boost::format("String is longer than %d symbols") % schema.Float()).str());
  227. return "";
  228. }
  229. static std::string minLengthCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  230. {
  231. if (data.String().size() < schema.Float())
  232. return validator.makeErrorMessage((boost::format("String is shorter than %d symbols") % schema.Float()).str());
  233. return "";
  234. }
  235. static std::string maximumCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  236. {
  237. if (data.Float() > schema.Float())
  238. return validator.makeErrorMessage((boost::format("Value is bigger than %d") % schema.Float()).str());
  239. return "";
  240. }
  241. static std::string minimumCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  242. {
  243. if (data.Float() < schema.Float())
  244. return validator.makeErrorMessage((boost::format("Value is smaller than %d") % schema.Float()).str());
  245. return "";
  246. }
  247. static std::string exclusiveMaximumCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  248. {
  249. if (data.Float() >= schema.Float())
  250. return validator.makeErrorMessage((boost::format("Value is bigger than %d") % schema.Float()).str());
  251. return "";
  252. }
  253. static std::string exclusiveMinimumCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  254. {
  255. if (data.Float() <= schema.Float())
  256. return validator.makeErrorMessage((boost::format("Value is smaller than %d") % schema.Float()).str());
  257. return "";
  258. }
  259. static std::string multipleOfCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  260. {
  261. double result = data.Integer() / schema.Integer();
  262. if (!vstd::isAlmostEqual(floor(result), result))
  263. return validator.makeErrorMessage((boost::format("Value is not divisible by %d") % schema.Float()).str());
  264. return "";
  265. }
  266. static std::string itemEntryCheck(JsonValidator & validator, const JsonVector & items, const JsonNode & schema, size_t index)
  267. {
  268. validator.currentPath.emplace_back();
  269. validator.currentPath.back().Float() = static_cast<double>(index);
  270. auto onExit = vstd::makeScopeGuard([&validator]()
  271. {
  272. validator.currentPath.pop_back();
  273. });
  274. if (!schema.isNull())
  275. return validator.check(schema, items[index]);
  276. return "";
  277. }
  278. static std::string itemsCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  279. {
  280. std::string errors;
  281. for (size_t i=0; i<data.Vector().size(); i++)
  282. {
  283. if (schema.getType() == JsonNode::JsonType::DATA_VECTOR)
  284. {
  285. if (schema.Vector().size() > i)
  286. errors += itemEntryCheck(validator, data.Vector(), schema.Vector()[i], i);
  287. }
  288. else
  289. {
  290. errors += itemEntryCheck(validator, data.Vector(), schema, i);
  291. }
  292. }
  293. return errors;
  294. }
  295. static std::string additionalItemsCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  296. {
  297. std::string errors;
  298. // "items" is struct or empty (defaults to empty struct) - validation always successful
  299. const JsonNode & items = baseSchema["items"];
  300. if (items.getType() != JsonNode::JsonType::DATA_VECTOR)
  301. return "";
  302. for (size_t i=items.Vector().size(); i<data.Vector().size(); i++)
  303. {
  304. if (schema.getType() == JsonNode::JsonType::DATA_STRUCT)
  305. errors += itemEntryCheck(validator, data.Vector(), schema, i);
  306. else if(!schema.isNull() && !schema.Bool())
  307. errors += validator.makeErrorMessage("Unknown entry found");
  308. }
  309. return errors;
  310. }
  311. static std::string minItemsCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  312. {
  313. if (data.Vector().size() < schema.Float())
  314. return validator.makeErrorMessage((boost::format("Length is smaller than %d") % schema.Float()).str());
  315. return "";
  316. }
  317. static std::string maxItemsCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  318. {
  319. if (data.Vector().size() > schema.Float())
  320. return validator.makeErrorMessage((boost::format("Length is bigger than %d") % schema.Float()).str());
  321. return "";
  322. }
  323. static std::string uniqueItemsCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  324. {
  325. if (schema.Bool())
  326. {
  327. for (auto itA = schema.Vector().begin(); itA != schema.Vector().end(); itA++)
  328. {
  329. auto itB = itA;
  330. while (++itB != schema.Vector().end())
  331. {
  332. if (*itA == *itB)
  333. return validator.makeErrorMessage("List must consist from unique items");
  334. }
  335. }
  336. }
  337. return "";
  338. }
  339. static std::string maxPropertiesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  340. {
  341. if (data.Struct().size() > schema.Float())
  342. return validator.makeErrorMessage((boost::format("Number of entries is bigger than %d") % schema.Float()).str());
  343. return "";
  344. }
  345. static std::string minPropertiesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  346. {
  347. if (data.Struct().size() < schema.Float())
  348. return validator.makeErrorMessage((boost::format("Number of entries is less than %d") % schema.Float()).str());
  349. return "";
  350. }
  351. static std::string uniquePropertiesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  352. {
  353. for (auto itA = data.Struct().begin(); itA != data.Struct().end(); itA++)
  354. {
  355. auto itB = itA;
  356. while (++itB != data.Struct().end())
  357. {
  358. if (itA->second == itB->second)
  359. return validator.makeErrorMessage("List must consist from unique items");
  360. }
  361. }
  362. return "";
  363. }
  364. static std::string requiredCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  365. {
  366. std::string errors;
  367. for(const auto & required : schema.Vector())
  368. {
  369. if (data[required.String()].isNull())
  370. errors += validator.makeErrorMessage("Required entry " + required.String() + " is missing");
  371. }
  372. return errors;
  373. }
  374. static std::string dependenciesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  375. {
  376. std::string errors;
  377. for(const auto & deps : schema.Struct())
  378. {
  379. if (!data[deps.first].isNull())
  380. {
  381. if (deps.second.getType() == JsonNode::JsonType::DATA_VECTOR)
  382. {
  383. JsonVector depList = deps.second.Vector();
  384. for(auto & depEntry : depList)
  385. {
  386. if (data[depEntry.String()].isNull())
  387. errors += validator.makeErrorMessage("Property " + depEntry.String() + " required for " + deps.first + " is missing");
  388. }
  389. }
  390. else
  391. {
  392. if (!validator.check(deps.second, data).empty())
  393. errors += validator.makeErrorMessage("Requirements for " + deps.first + " are not fulfilled");
  394. }
  395. }
  396. }
  397. return errors;
  398. }
  399. static std::string propertyEntryCheck(JsonValidator & validator, const JsonNode &node, const JsonNode & schema, const std::string & nodeName)
  400. {
  401. validator.currentPath.emplace_back();
  402. validator.currentPath.back().String() = nodeName;
  403. auto onExit = vstd::makeScopeGuard([&validator]()
  404. {
  405. validator.currentPath.pop_back();
  406. });
  407. // there is schema specifically for this item
  408. if (!schema.isNull())
  409. return validator.check(schema, node);
  410. return "";
  411. }
  412. static std::string propertiesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  413. {
  414. std::string errors;
  415. for(const auto & entry : data.Struct())
  416. errors += propertyEntryCheck(validator, entry.second, schema[entry.first], entry.first);
  417. return errors;
  418. }
  419. static std::string additionalPropertiesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  420. {
  421. std::string errors;
  422. for(const auto & entry : data.Struct())
  423. {
  424. if (baseSchema["properties"].Struct().count(entry.first) == 0)
  425. {
  426. // try generic additionalItems schema
  427. if (schema.getType() == JsonNode::JsonType::DATA_STRUCT)
  428. errors += propertyEntryCheck(validator, entry.second, schema, entry.first);
  429. // or, additionalItems field can be bool which indicates if such items are allowed
  430. else if(!schema.isNull() && !schema.Bool()) // present and set to false - error
  431. {
  432. std::string bestCandidate = findClosestMatch(baseSchema["properties"].Struct(), entry.first);
  433. if (!bestCandidate.empty())
  434. errors += validator.makeErrorMessage("Unknown entry found: '" + entry.first + "'. Perhaps you meant '" + bestCandidate + "'?");
  435. else
  436. errors += validator.makeErrorMessage("Unknown entry found: " + entry.first);
  437. }
  438. }
  439. }
  440. return errors;
  441. }
  442. static bool testFilePresence(const std::string & scope, const ResourcePath & resource)
  443. {
  444. #ifndef ENABLE_MINIMAL_LIB
  445. std::set<std::string> allowedScopes;
  446. if(scope != ModScope::scopeBuiltin() && !scope.empty()) // all real mods may have dependencies
  447. {
  448. //NOTE: recursive dependencies are not allowed at the moment - update code if this changes
  449. bool found = true;
  450. allowedScopes = VLC->modh->getModDependencies(scope, found);
  451. if(!found)
  452. return false;
  453. allowedScopes.insert(ModScope::scopeBuiltin()); // all mods can use H3 files
  454. }
  455. allowedScopes.insert(scope); // mods can use their own files
  456. for(const auto & entry : allowedScopes)
  457. {
  458. if (CResourceHandler::get(entry)->existsResource(resource))
  459. return true;
  460. }
  461. #endif
  462. return false;
  463. }
  464. #define TEST_FILE(scope, prefix, file, type) \
  465. if (testFilePresence(scope, ResourcePath(prefix + file, type))) \
  466. return ""
  467. static std::string testAnimation(const std::string & path, const std::string & scope)
  468. {
  469. TEST_FILE(scope, "Sprites/", path, EResType::ANIMATION);
  470. TEST_FILE(scope, "Sprites/", path, EResType::JSON);
  471. return "Animation file \"" + path + "\" was not found";
  472. }
  473. static std::string textFile(const JsonNode & node)
  474. {
  475. TEST_FILE(node.getModScope(), "", node.String(), EResType::JSON);
  476. return "Text file \"" + node.String() + "\" was not found";
  477. }
  478. static std::string musicFile(const JsonNode & node)
  479. {
  480. TEST_FILE(node.getModScope(), "Music/", node.String(), EResType::SOUND);
  481. TEST_FILE(node.getModScope(), "", node.String(), EResType::SOUND);
  482. return "Music file \"" + node.String() + "\" was not found";
  483. }
  484. static std::string soundFile(const JsonNode & node)
  485. {
  486. TEST_FILE(node.getModScope(), "Sounds/", node.String(), EResType::SOUND);
  487. return "Sound file \"" + node.String() + "\" was not found";
  488. }
  489. static std::string animationFile(const JsonNode & node)
  490. {
  491. return testAnimation(node.String(), node.getModScope());
  492. }
  493. static std::string imageFile(const JsonNode & node)
  494. {
  495. TEST_FILE(node.getModScope(), "Data/", node.String(), EResType::IMAGE);
  496. TEST_FILE(node.getModScope(), "Sprites/", node.String(), EResType::IMAGE);
  497. if (node.String().find(':') != std::string::npos)
  498. return testAnimation(node.String().substr(0, node.String().find(':')), node.getModScope());
  499. return "Image file \"" + node.String() + "\" was not found";
  500. }
  501. static std::string videoFile(const JsonNode & node)
  502. {
  503. TEST_FILE(node.getModScope(), "Video/", node.String(), EResType::VIDEO);
  504. TEST_FILE(node.getModScope(), "Video/", node.String(), EResType::VIDEO_LOW_QUALITY);
  505. return "Video file \"" + node.String() + "\" was not found";
  506. }
  507. #undef TEST_FILE
  508. JsonValidator::TValidatorMap createCommonFields()
  509. {
  510. JsonValidator::TValidatorMap ret;
  511. ret["format"] = formatCheck;
  512. ret["allOf"] = allOfCheck;
  513. ret["anyOf"] = anyOfCheck;
  514. ret["oneOf"] = oneOfCheck;
  515. ret["enum"] = enumCheck;
  516. ret["const"] = constCheck;
  517. ret["type"] = typeCheck;
  518. ret["not"] = notCheck;
  519. ret["$ref"] = refCheck;
  520. // fields that don't need implementation
  521. ret["title"] = emptyCheck;
  522. ret["$schema"] = emptyCheck;
  523. ret["default"] = emptyCheck;
  524. ret["defaultIOS"] = emptyCheck;
  525. ret["defaultAndroid"] = emptyCheck;
  526. ret["defaultWindows"] = emptyCheck;
  527. ret["description"] = emptyCheck;
  528. ret["definitions"] = emptyCheck;
  529. // Not implemented
  530. ret["propertyNames"] = notImplementedCheck;
  531. ret["contains"] = notImplementedCheck;
  532. ret["examples"] = notImplementedCheck;
  533. return ret;
  534. }
  535. JsonValidator::TValidatorMap createStringFields()
  536. {
  537. JsonValidator::TValidatorMap ret = createCommonFields();
  538. ret["maxLength"] = maxLengthCheck;
  539. ret["minLength"] = minLengthCheck;
  540. ret["pattern"] = notImplementedCheck;
  541. return ret;
  542. }
  543. JsonValidator::TValidatorMap createNumberFields()
  544. {
  545. JsonValidator::TValidatorMap ret = createCommonFields();
  546. ret["maximum"] = maximumCheck;
  547. ret["minimum"] = minimumCheck;
  548. ret["multipleOf"] = multipleOfCheck;
  549. ret["exclusiveMaximum"] = exclusiveMaximumCheck;
  550. ret["exclusiveMinimum"] = exclusiveMinimumCheck;
  551. return ret;
  552. }
  553. JsonValidator::TValidatorMap createVectorFields()
  554. {
  555. JsonValidator::TValidatorMap ret = createCommonFields();
  556. ret["items"] = itemsCheck;
  557. ret["minItems"] = minItemsCheck;
  558. ret["maxItems"] = maxItemsCheck;
  559. ret["uniqueItems"] = uniqueItemsCheck;
  560. ret["additionalItems"] = additionalItemsCheck;
  561. return ret;
  562. }
  563. JsonValidator::TValidatorMap createStructFields()
  564. {
  565. JsonValidator::TValidatorMap ret = createCommonFields();
  566. ret["additionalProperties"] = additionalPropertiesCheck;
  567. ret["uniqueProperties"] = uniquePropertiesCheck;
  568. ret["maxProperties"] = maxPropertiesCheck;
  569. ret["minProperties"] = minPropertiesCheck;
  570. ret["dependencies"] = dependenciesCheck;
  571. ret["properties"] = propertiesCheck;
  572. ret["required"] = requiredCheck;
  573. ret["patternProperties"] = notImplementedCheck;
  574. return ret;
  575. }
  576. JsonValidator::TFormatMap createFormatMap()
  577. {
  578. JsonValidator::TFormatMap ret;
  579. ret["textFile"] = textFile;
  580. ret["musicFile"] = musicFile;
  581. ret["soundFile"] = soundFile;
  582. ret["animationFile"] = animationFile;
  583. ret["imageFile"] = imageFile;
  584. ret["videoFile"] = videoFile;
  585. //TODO:
  586. // uri-reference
  587. // uri-template
  588. // json-pointer
  589. return ret;
  590. }
  591. std::string JsonValidator::makeErrorMessage(const std::string &message)
  592. {
  593. std::string errors;
  594. errors += "At ";
  595. if (!currentPath.empty())
  596. {
  597. for(const JsonNode &path : currentPath)
  598. {
  599. errors += "/";
  600. if (path.getType() == JsonNode::JsonType::DATA_STRING)
  601. errors += path.String();
  602. else
  603. errors += std::to_string(static_cast<unsigned>(path.Float()));
  604. }
  605. }
  606. else
  607. errors += "<root>";
  608. errors += "\n\t Error: " + message + "\n";
  609. return errors;
  610. }
  611. std::string JsonValidator::check(const std::string & schemaName, const JsonNode & data)
  612. {
  613. usedSchemas.push_back(schemaName);
  614. auto onscopeExit = vstd::makeScopeGuard([this]()
  615. {
  616. usedSchemas.pop_back();
  617. });
  618. return check(JsonUtils::getSchema(schemaName), data);
  619. }
  620. std::string JsonValidator::check(const JsonNode & schema, const JsonNode & data)
  621. {
  622. const TValidatorMap & knownFields = getKnownFieldsFor(data.getType());
  623. std::string errors;
  624. for(const auto & entry : schema.Struct())
  625. {
  626. auto checker = knownFields.find(entry.first);
  627. if (checker != knownFields.end())
  628. errors += checker->second(*this, schema, entry.second, data);
  629. }
  630. return errors;
  631. }
  632. const JsonValidator::TValidatorMap & JsonValidator::getKnownFieldsFor(JsonNode::JsonType type)
  633. {
  634. static const TValidatorMap commonFields = createCommonFields();
  635. static const TValidatorMap numberFields = createNumberFields();
  636. static const TValidatorMap stringFields = createStringFields();
  637. static const TValidatorMap vectorFields = createVectorFields();
  638. static const TValidatorMap structFields = createStructFields();
  639. switch (type)
  640. {
  641. case JsonNode::JsonType::DATA_FLOAT:
  642. case JsonNode::JsonType::DATA_INTEGER:
  643. return numberFields;
  644. case JsonNode::JsonType::DATA_STRING: return stringFields;
  645. case JsonNode::JsonType::DATA_VECTOR: return vectorFields;
  646. case JsonNode::JsonType::DATA_STRUCT: return structFields;
  647. default: return commonFields;
  648. }
  649. }
  650. const JsonValidator::TFormatMap & JsonValidator::getKnownFormats()
  651. {
  652. static const TFormatMap knownFormats = createFormatMap();
  653. return knownFormats;
  654. }
  655. VCMI_LIB_NAMESPACE_END