- Now possible to call objects within objects from a variabl

This commit is contained in:
Dave M. 2023-07-09 12:40:16 -04:00
parent f92baa03c8
commit 114d4ebe1e
1 changed files with 17 additions and 8 deletions

View File

@ -49,6 +49,17 @@ class Iterate
return false; return false;
} }
# Parses $obj1.obj2.obj3.propery
protected static function objectFromPath(object $object, array $pathArr) : array
{
while(count($pathArr) > 1) {
$propertyName = array_shift($pathArr);
$object = $object->$propertyName;
}
return [ $object, end($pathArr) ];
}
public static function arrayGet(iterable $array, string $path, string $delimiter = '.') { public static function arrayGet(iterable $array, string $path, string $delimiter = '.') {
$pathArr = explode($delimiter, $path); $pathArr = explode($delimiter, $path);
@ -58,14 +69,12 @@ class Iterate
if ( ! is_iterable($recurse) ) { if ( ! is_iterable($recurse) ) {
if ( is_object($recurse) ) { if ( is_object($recurse) ) {
if ( count($pathArr) > 1 ) { list($object, $method) = static::objectFromPath($recurse, $pathArr);
throw new \Exception("An error occured trying to fetch a value from an object using path '$path'");
} # @TODO An object caller would be a WAY better idea then this line of code
else { # Calling $obj->varname
# @TODO An object caller would be a WAY better idea then this line of code
# Calling $obj->varname return $object->$method ?? "";
return $recurse->{$pathArr[0]} ?? "";
}
} }
elseif (is_scalar($recurse)) { elseif (is_scalar($recurse)) {
throw new \Exception("An error occured trying to fetch a value from a scalar value using path '$path'"); throw new \Exception("An error occured trying to fetch a value from a scalar value using path '$path'");