From 6bbadfc6b1eaf14f68a27cb8e378f5e09ab38de6 Mon Sep 17 00:00:00 2001 From: Yuqian Yang Date: Mon, 15 Dec 2025 22:05:52 +0800 Subject: Extract out MapFromXmlAsStringValue. --- include/cru/ui/mapper/Mapper.h | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) (limited to 'include/cru/ui/mapper/Mapper.h') diff --git a/include/cru/ui/mapper/Mapper.h b/include/cru/ui/mapper/Mapper.h index 68ad2ab0..e9e7b851 100644 --- a/include/cru/ui/mapper/Mapper.h +++ b/include/cru/ui/mapper/Mapper.h @@ -6,7 +6,7 @@ #include #include -#include +#include #include namespace cru::ui::mapper { @@ -35,12 +35,9 @@ class CRU_UI_API MapperBase : public Object { template class CRU_UI_API BasicMapper : public MapperBase { public: - static_assert(std::is_default_constructible_v, - "T must be default constructible."); - BasicMapper() : MapperBase(typeid(T)) {} - virtual T MapFromString(std::string str) { + T MapFromString(std::string str) { if (!SupportMapFromString()) { throw Exception("This mapper does not support map from string."); } @@ -61,8 +58,36 @@ class CRU_UI_API BasicMapper : public MapperBase { } protected: - virtual T DoMapFromString(std::string str) { return {}; } - virtual T DoMapFromXml(xml::XmlElementNode* node) { return {}; } + virtual T DoMapFromString(std::string str) { NotImplemented(); } + virtual T DoMapFromXml(xml::XmlElementNode* node) { NotImplemented(); } + + T MapFromXmlAsStringValue(xml::XmlElementNode* node, + std::optional default_value = std::nullopt) { + std::optional& value = default_value; + + auto value_attr = node->GetOptionalAttributeValueCaseInsensitive("value"); + if (value_attr) { + value = DoMapFromString(*value_attr); + } + + for (auto child : node->GetChildren()) { + if (child->IsElementNode()) { + throw MapException("XML node can't contain element child."); + } else if (auto c = child->AsText()) { + auto text = c->GetText(); + if (!text.empty() && value.has_value()) { + throw MapException("XML node has multiple values specified."); + } + value = DoMapFromString(text); + } + } + + if (!value.has_value()) { + throw MapException("XML node has no value specified."); + } + + return *value; + } }; template -- cgit v1.2.3