validator.h 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. #pragma once
  2. #include <regex>
  3. #include <unordered_map>
  4. #include <jvalidate/detail/on_block_exit.h>
  5. #include <jvalidate/forward.h>
  6. #include <jvalidate/status.h>
  7. #include <jvalidate/validation_config.h>
  8. #include <jvalidate/validation_visitor.h>
  9. namespace jvalidate::detail {
  10. /**
  11. * @brief An implementation of a regular expression "engine", for use with
  12. * constraints like "pattern" and "patternProperties".
  13. * Uses std::regex as its underlying implementation.
  14. *
  15. * While being std::regex means that it is the most sensible choice for a
  16. * default RegexEngine, the performance of std::regex is generally the worst
  17. * among C++ regex utilities, and it struggles to compile several patterns.
  18. * See https://stackoverflow.com/questions/70583395/ for an explaination.
  19. *
  20. * If you need to use complicated patterns in your json schema, provide a
  21. * RegexEngine compatible wrapper for a different library, such as re2.
  22. */
  23. class StdRegexEngine {
  24. private:
  25. std::unordered_map<std::string, std::regex> cache_;
  26. public:
  27. static std::string_view engine_name() { return "std::regex[ECMAScript]"; }
  28. bool search(std::string const & regex, std::string const & text) {
  29. auto const & re = cache_.try_emplace(regex, regex).first->second;
  30. return std::regex_search(text, re);
  31. }
  32. };
  33. /**
  34. * @brief An implementation of an "Extension Constraint Visitor" plugin that
  35. * does nothing.
  36. */
  37. struct StubExtensionVisitor {};
  38. }
  39. namespace jvalidate {
  40. /**
  41. * @brief A validator is the tool by which a JSON object is actually validated
  42. * against a schema.
  43. *
  44. * @tparam RE A type that can be used to solve regular expressions
  45. */
  46. template <RegexEngine RE = detail::StdRegexEngine,
  47. typename ExtensionVisitor = detail::StubExtensionVisitor>
  48. class Validator {
  49. private:
  50. schema::Node const & schema_;
  51. ValidationConfig cfg_;
  52. ExtensionVisitor extension_;
  53. RE regex_;
  54. public:
  55. /**
  56. * @brief Construct a Validator
  57. *
  58. * @param schema The root schema being validated against. Must outlive this.
  59. *
  60. * @param cfg Any special (runtime) configuration rules being applied to the
  61. * validator.
  62. */
  63. Validator(schema::Node const & schema, ExtensionVisitor extension = {},
  64. ValidationConfig const & cfg = {})
  65. : schema_(schema), cfg_(cfg), extension_(extension) {}
  66. Validator(schema::Node const & schema, ValidationConfig const & cfg)
  67. : schema_(schema), cfg_(cfg) {}
  68. template <typename... Args> Validator(schema::Node &&, Args &&...) = delete;
  69. /**
  70. * @brief Run validation on the given JSON
  71. *
  72. * @tparam A Any Adapter type, in principle a subclass of adapter::Adapter.
  73. * Disallows mutation via ValidationConfig.construct_default_values
  74. *
  75. * @param json The value being validated
  76. *
  77. * @param result An optional out-param of detailed information about
  78. * validation failures. If result is not provided, then the validator will
  79. * terminate on the first error. Otherwise it will run through the entire
  80. * schema to provide a record of all of the failures.
  81. */
  82. template <Adapter A>
  83. requires(not MutableAdapter<A>)
  84. bool validate(A const & json, ValidationResult * result = nullptr) {
  85. EXPECT_M(not cfg_.construct_default_values,
  86. "Cannot perform mutations on an immutable JSON Adapter");
  87. detail::OnBlockExit _ = [&result, this]() { post_process(result); };
  88. return static_cast<bool>(
  89. ValidationVisitor(schema_, cfg_, regex_, extension_, result).validate(json));
  90. }
  91. /**
  92. * @brief Run validation on the given JSON
  93. *
  94. * @tparam A Any Adapter type that supports assignment, in principle a
  95. * subclass of adapter::Adapter.
  96. *
  97. * @param json The value being validated. Because A is a reference-wrapper,
  98. * the underlying value may be mutated.
  99. *
  100. * @param result An optional out-param of detailed information about
  101. * validation failures. If result is not provided, then the validator will
  102. * terminate on the first error. Otherwise it will run through the entire
  103. * schema to provide a record of all of the failures.
  104. */
  105. template <MutableAdapter A> bool validate(A const & json, ValidationResult * result = nullptr) {
  106. detail::OnBlockExit _ = [&result, this]() { post_process(result); };
  107. return static_cast<bool>(
  108. ValidationVisitor(schema_, cfg_, regex_, extension_, result).validate(json));
  109. }
  110. /**
  111. * @brief Run validation on the given JSON
  112. *
  113. * @tparam JSON A concrete JSON type. Will be turned into an Adapter, or a
  114. * MutableAdapter (if json is non-const and exists).
  115. *
  116. * @param json The value being validated.
  117. *
  118. * @param result An optional out-param of detailed information about
  119. * validation failures. If result is not provided, then the validator will
  120. * terminate on the first error. Otherwise it will run through the entire
  121. * schema to provide a record of all of the failures.
  122. */
  123. template <typename JSON>
  124. requires(not Adapter<JSON>)
  125. bool validate(JSON & json, ValidationResult * result = nullptr) {
  126. return validate(adapter::AdapterFor<JSON>(json), result);
  127. }
  128. private:
  129. void post_process(ValidationResult *& result) const {
  130. if (result == nullptr) {
  131. return;
  132. }
  133. if (cfg_.only_return_results_with_error) {
  134. *result = result->only_errors();
  135. }
  136. }
  137. };
  138. }