validator.h 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. bool search(std::string const & regex, std::string const & text) {
  28. auto const & re = cache_.try_emplace(regex, regex).first->second;
  29. return std::regex_search(text, re);
  30. }
  31. };
  32. /**
  33. * @brief An implementation of an "Extension Constraint Visitor" plugin that
  34. * does nothing.
  35. */
  36. struct StubExtensionVisitor {};
  37. }
  38. namespace jvalidate {
  39. /**
  40. * @brief A validator is the tool by which a JSON object is actually validated
  41. * against a schema.
  42. *
  43. * @tparam RE A type that can be used to solve regular expressions
  44. */
  45. template <RegexEngine RE = detail::StdRegexEngine,
  46. typename ExtensionVisitor = detail::StubExtensionVisitor>
  47. class Validator {
  48. private:
  49. schema::Node const & schema_;
  50. ValidationConfig cfg_;
  51. ExtensionVisitor extension_;
  52. RE regex_;
  53. public:
  54. /**
  55. * @brief Construct a Validator
  56. *
  57. * @param schema The root schema being validated against. Must outlive this.
  58. *
  59. * @param cfg Any special (runtime) configuration rules being applied to the
  60. * validator.
  61. */
  62. Validator(schema::Node const & schema, ExtensionVisitor extension = {},
  63. ValidationConfig const & cfg = {})
  64. : schema_(schema), cfg_(cfg), extension_(extension) {}
  65. Validator(schema::Node const & schema, ValidationConfig const & cfg)
  66. : schema_(schema), cfg_(cfg) {}
  67. template <typename... Args> Validator(schema::Node &&, Args &&...) = delete;
  68. /**
  69. * @brief Run validation on the given JSON
  70. *
  71. * @tparam A Any Adapter type, in principle a subclass of adapter::Adapter.
  72. * Disallows mutation via ValidationConfig.construct_default_values
  73. *
  74. * @param json The value being validated
  75. *
  76. * @param result An optional out-param of detailed information about
  77. * validation failures. If result is not provided, then the validator will
  78. * terminate on the first error. Otherwise it will run through the entire
  79. * schema to provide a record of all of the failures.
  80. */
  81. template <Adapter A>
  82. requires(not MutableAdapter<A>)
  83. bool validate(A const & json, ValidationResult * result = nullptr) {
  84. EXPECT_M(not cfg_.construct_default_values,
  85. "Cannot perform mutations on an immutable JSON Adapter");
  86. detail::OnBlockExit _ = [&result, this]() { post_process(result); };
  87. return static_cast<bool>(
  88. ValidationVisitor(schema_, cfg_, regex_, extension_, result).validate(json));
  89. }
  90. /**
  91. * @brief Run validation on the given JSON
  92. *
  93. * @tparam A Any Adapter type that supports assignment, in principle a
  94. * subclass of adapter::Adapter.
  95. *
  96. * @param json The value being validated. Because A is a reference-wrapper,
  97. * the underlying value may be mutated.
  98. *
  99. * @param result An optional out-param of detailed information about
  100. * validation failures. If result is not provided, then the validator will
  101. * terminate on the first error. Otherwise it will run through the entire
  102. * schema to provide a record of all of the failures.
  103. */
  104. template <MutableAdapter A> bool validate(A const & json, ValidationResult * result = nullptr) {
  105. detail::OnBlockExit _ = [&result, this]() { post_process(result); };
  106. return static_cast<bool>(
  107. ValidationVisitor(schema_, cfg_, regex_, extension_, result).validate(json));
  108. }
  109. /**
  110. * @brief Run validation on the given JSON
  111. *
  112. * @tparam JSON A concrete JSON type. Will be turned into an Adapter, or a
  113. * MutableAdapter (if json is non-const and exists).
  114. *
  115. * @param json The value being validated.
  116. *
  117. * @param result An optional out-param of detailed information about
  118. * validation failures. If result is not provided, then the validator will
  119. * terminate on the first error. Otherwise it will run through the entire
  120. * schema to provide a record of all of the failures.
  121. */
  122. template <typename JSON>
  123. requires(not Adapter<JSON>)
  124. bool validate(JSON & json, ValidationResult * result = nullptr) {
  125. return validate(adapter::AdapterFor<JSON>(json), result);
  126. }
  127. private:
  128. void post_process(ValidationResult *& result) const {
  129. if (result == nullptr) {
  130. return;
  131. }
  132. if (cfg_.only_return_results_with_error) {
  133. *result = result->only_errors();
  134. }
  135. }
  136. };
  137. }