ConfigManager.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #pragma once
  2. #include <string>
  3. #include <fstream>
  4. #include "ConfigField.h"
  5. #include "../Utils/util.h"
  6. #include "../Utils/Logger.h"
  7. #include "../api/json/json.hpp"
  8. using json = nlohmann::json;
  9. namespace config {
  10. void save(json config);
  11. template <typename T>
  12. ConfigField<T> getValue(const std::string& path, const std::string& key, const T& defaultValue) {
  13. std::ifstream configFile("minty.json");
  14. json configRoot;
  15. configFile >> configRoot;
  16. configFile.close();
  17. if (path.find(":") != std::string::npos) {
  18. auto sections = util::split(path, ":");
  19. for (auto& section : sections)
  20. configRoot = configRoot[section];
  21. if (configRoot.find(key) != configRoot.end())
  22. return ConfigField<T>(path, key, configRoot[key]);
  23. }
  24. if (configRoot.find(path) != configRoot.end() && configRoot[path].find(key) != configRoot[path].end())
  25. return ConfigField<T>(path, key, configRoot[path][key]);
  26. return ConfigField<T>(path, key, defaultValue);
  27. }
  28. template<typename T>
  29. void setValue(const std::string& path, const std::string& key, const T& newValue) {
  30. std::ifstream configFile("minty.json");
  31. json configRoot;
  32. configFile >> configRoot;
  33. configFile.close();
  34. json* configTemp = &configRoot;
  35. if (path.find(":") != std::string::npos) {
  36. auto sections = util::split(path, ":");
  37. for (auto& section : sections) {
  38. if (!configTemp->contains(section))
  39. (*configTemp)[section] = {};
  40. configTemp = &(*configTemp)[section];
  41. }
  42. (*configTemp)[key] = newValue;
  43. save(configRoot);
  44. return;
  45. }
  46. configRoot[path][key] = newValue;
  47. save(configRoot);
  48. }
  49. template<typename T>
  50. void setValue(ConfigField<T>& field, const T& newValue) {
  51. setValue(field.getPath(), field.getKey(), newValue);
  52. }
  53. }