SerializableJSONState.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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-26
  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) :
  13. ls_std::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. std::shared_ptr<ls_std::State> ls_std::SerializableJSONState::getValue()
  29. {
  30. return this->value;
  31. }
  32. void ls_std::SerializableJSONState::setValue(const std::shared_ptr<ls_std::State>& _value)
  33. {
  34. this->_assignValue(_value);
  35. this->_clear();
  36. }
  37. void ls_std::SerializableJSONState::_assignValue(const std::shared_ptr<ls_std::State> &_value)
  38. {
  39. if(_value == nullptr) {
  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. this->value->clearConnections();
  52. for(const auto& connectionJSON : this->jsonObject["connectedStates"]) {
  53. std::shared_ptr<ls_std::StateConnection> connection = std::make_shared<ls_std::StateConnection>("TMP_ID", "TMP_ID");
  54. ls_std::SerializableJSONStateConnection{connection}.unmarshal(connectionJSON.dump());
  55. this->value->addStateConnection(connection);
  56. }
  57. }
  58. }
  59. void ls_std::SerializableJSONState::_update()
  60. {
  61. this->jsonObject = {
  62. {"id", this->value->getId()}
  63. };
  64. this->_updateStateConnections();
  65. }
  66. void ls_std::SerializableJSONState::_updateStateConnections()
  67. {
  68. std::string jsonString {};
  69. for(const auto& connection : this->value->getConnectedStates()) {
  70. jsonString = ls_std::SerializableJSONStateConnection{connection.second}.marshal();
  71. this->jsonObject["connectedStates"][connection.first] = nlohmann::json::parse(jsonString);
  72. }
  73. }