diff --git a/docs/array_get.md b/docs/array_get.md new file mode 100644 index 0000000..c39c7c7 --- /dev/null +++ b/docs/array_get.md @@ -0,0 +1,39 @@ +# array_get + +Get an item from an array using "dot" notation. + +## Parameters + +* array (`array`, `instruction`) - The array to get the value from. +* key (`string`, `instruction`) - The key to get the value for. + +## Return + +(mixed) - The value of the key or throws an exception if the key is not found. + +## Exceptions + +* `EvaluationException` - If there was an error while evaluating one or more parameters. +* `KeyException` - If the key is not found. +* `TypeException` - If one or more parameters are not of the expected type. + +## Instruction Example + +```json +{ + "type": "array_get", + "_": { + "array": { + "foo": { + "bar": "baz" + } + }, + "key": "foo.bar" + } +} +``` + +### Last Updated + +Monday, December 26th, 2022. +Written by [Netkas](https://git.n64.cc/netkas) \ No newline at end of file diff --git a/src/RTEX/Objects/Program/Instructions/ArrayGet.php b/src/RTEX/Objects/Program/Instructions/ArrayGet.php index a3a70c4..f8ff5e0 100644 --- a/src/RTEX/Objects/Program/Instructions/ArrayGet.php +++ b/src/RTEX/Objects/Program/Instructions/ArrayGet.php @@ -11,6 +11,7 @@ use RTEX\Exceptions\EvaluationException; use RTEX\Exceptions\InstructionException; use RTEX\Exceptions\Runtime\KeyException; + use RTEX\Exceptions\Runtime\TypeException; use RTEX\Interfaces\InstructionInterface; class ArrayGet implements InstructionInterface @@ -111,23 +112,33 @@ * @return mixed * @throws EvaluationException * @throws KeyException + * @throws TypeException */ public function eval(Engine $engine): mixed { - $queryParts = explode('.', $engine->eval($this->Value)); - $value = $engine->getEnvironment()->getRuntimeVariable($engine->eval($this->Array)); + $value = $engine->eval($this->Value); + $array = $engine->eval($this->Array); - foreach ($queryParts as $queryPart) + if (!is_array($array)) + throw new KeyException(sprintf('Cannot read from non-array value of type %s', Utilities::getType($array))); + if(!is_string($value) && !is_int($value)) + throw new TypeException(sprintf('Cannot read from array with non-string value %s', Utilities::getType($value))); + + $keys = explode('.', $value); + $result = $array; + foreach ($keys as $key) { - if (is_array($value) && array_key_exists($queryPart, $value)) + if (is_array($result) && array_key_exists($key, $result)) { - return $value[$queryPart]; + $result = $result[$key]; + } + else + { + throw new KeyException(sprintf('Key "%s" does not exist in array (%s)', $key, $value)); } - - throw new KeyException(sprintf('Key "%s" does not exist in array', $queryPart)); } - return $value; + return $result; } /**