SerializableJSONState.cpp 2.3 KB

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