SerializableJSONState.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Company: Lynar Studios
  4. * E-Mail: webmaster@lynarstudios.com
  5. * Created: 2020-09-15
  6. * Changed: 2021-04-23
  7. *
  8. * */
  9. #include <ls_std/serialization/logic/SerializableJSONState.hpp>
  10. #include <ls_std/serialization/logic/SerializableJSONStateConnection.hpp>
  11. #include <ls_std/exception/IllegalArgumentException.hpp>
  12. ls_std::SerializableJSONState::SerializableJSONState(const std::shared_ptr<ls_std::State> &_value) : ls_std::Class("SerializableJSONState")
  13. {
  14. this->_assignValue(_value);
  15. }
  16. ls_std::byte_field ls_std::SerializableJSONState::marshal()
  17. {
  18. this->_update();
  19. return this->jsonObject.dump();
  20. }
  21. void ls_std::SerializableJSONState::unmarshal(const ls_std::byte_field &_data)
  22. {
  23. this->jsonObject = nlohmann::json::parse(_data);
  24. this->_unmarshalStateConnections();
  25. this->value->setId(this->jsonObject["id"]);
  26. }
  27. std::shared_ptr<ls_std::State> ls_std::SerializableJSONState::getValue()
  28. {
  29. return this->value;
  30. }
  31. void ls_std::SerializableJSONState::setValue(const std::shared_ptr<ls_std::State> &_value)
  32. {
  33. this->_assignValue(_value);
  34. this->_clear();
  35. }
  36. void ls_std::SerializableJSONState::_assignValue(const std::shared_ptr<ls_std::State> &_value)
  37. {
  38. if (_value == nullptr)
  39. {
  40. throw ls_std::IllegalArgumentException{};
  41. }
  42. this->value = _value;
  43. }
  44. void ls_std::SerializableJSONState::_clear()
  45. {
  46. this->jsonObject.clear();
  47. }
  48. void ls_std::SerializableJSONState::_unmarshalStateConnections()
  49. {
  50. if (!this->jsonObject["connectedStates"].empty())
  51. {
  52. this->value->clearConnections();
  53. for (const auto &connectionJSON : this->jsonObject["connectedStates"])
  54. {
  55. std::shared_ptr<ls_std::StateConnection> connection = std::make_shared<ls_std::StateConnection>("TMP_ID", "TMP_ID");
  56. ls_std::SerializableJSONStateConnection{connection}.unmarshal(connectionJSON.dump());
  57. this->value->addStateConnection(connection);
  58. }
  59. }
  60. }
  61. void ls_std::SerializableJSONState::_update()
  62. {
  63. this->jsonObject = {{"id", this->value->getId()}};
  64. this->_updateStateConnections();
  65. }
  66. void ls_std::SerializableJSONState::_updateStateConnections()
  67. {
  68. std::string jsonString{};
  69. for (const auto &connection : this->value->getConnectedStates())
  70. {
  71. jsonString = ls_std::SerializableJSONStateConnection{connection.second}.marshal();
  72. this->jsonObject["connectedStates"][connection.first] = nlohmann::json::parse(jsonString);
  73. }
  74. }