From e3673755dec2b907467c30c8a5e856543dfa5a0c Mon Sep 17 00:00:00 2001 From: Mike Bierlee Date: Sat, 24 Sep 2022 02:07:31 +0300 Subject: [PATCH] Make it possible to get a value from a root object --- source/poodinis/config/dictionary.d | 45 ++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/source/poodinis/config/dictionary.d b/source/poodinis/config/dictionary.d index ea0e86b..79de2ee 100644 --- a/source/poodinis/config/dictionary.d +++ b/source/poodinis/config/dictionary.d @@ -49,6 +49,12 @@ class ObjectNode : ConfigNode { this(ConfigNode[string] children) { this.children = children; } + + this(string[string] values) { + foreach (key, value; values) { + children[key] = new ValueNode(value); + } + } } class ArrayNode : ConfigNode { @@ -79,6 +85,14 @@ class ArrayPathSegment : PathSegment { } } +class PropertyPathSegment : PathSegment { + const string propertyName; + + this(const string propertyName) { + this.propertyName = propertyName; + } +} + class ConfigPath { private const string path; private string[] segments; @@ -114,7 +128,7 @@ class ConfigPath { } } - throw new Exception("Not yet implemented"); + return ret(new PropertyPathSegment(segment)); } } @@ -142,10 +156,25 @@ class ConfigDictionary { if (arrayPath) { auto arrayNode = cast(ArrayNode) currentNode; if (arrayNode) { + if (arrayNode.children.length < arrayPath.index) { + throw new ConfigReadException("Array index out of bounds: " ~ configPath); + } + currentNode = arrayNode.children[arrayPath.index]; } } + auto propertyPath = cast(PropertyPathSegment) currentPathSegment; + if (propertyPath) { + auto objectNode = cast(ObjectNode) currentNode; + if (objectNode) { + auto propertyNode = propertyPath.propertyName in objectNode.children; + if (propertyNode) { + currentNode = *propertyNode; + } + } + } + currentPathSegment = path.getNextSegment(); } @@ -213,4 +242,18 @@ version (unittest) { assert(dictionary.get("[1]") == "noot"); assert(dictionary.get("[2]") == "mies"); } + + @("Get value from object at root") + unittest { + auto dictionary = new ConfigDictionary(); + dictionary.rootNode = new ObjectNode([ + "aap": "monkey", + "noot": "nut", + "mies": "mies" // It's a name! + ]); + + assert(dictionary.get("aap") == "monkey"); + assert(dictionary.get("noot") == "nut"); + assert(dictionary.get("mies") == "mies"); + } }