From 951d9a3b102d07d5acf0eda0f1a41cd381012040 Mon Sep 17 00:00:00 2001 From: Greg Bowler Date: Thu, 29 Feb 2024 14:21:24 +0000 Subject: [PATCH] tweak: check method or property of object closes #489 --- src/BindableCache.php | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/src/BindableCache.php b/src/BindableCache.php index 7438cc4..5d0731a 100644 --- a/src/BindableCache.php +++ b/src/BindableCache.php @@ -2,6 +2,7 @@ namespace Gt\DomTemplate; use Closure; +use Error; use ReflectionAttribute; use ReflectionClass; use ReflectionMethod; @@ -70,7 +71,8 @@ public function isBindable(object $object):bool { foreach($refAttributes as $refAttr) { $bindKey = $this->getBindKey($refAttr, $refMethod); - $attributeCache[$bindKey] = fn(object $object):null|iterable|string => $this->nullableStringOrIterable($object->$methodName()); + $attributeCache[$bindKey] = fn(object $object):null|iterable|string => $this->nullableStringOrIterable($object, $methodName); + if(class_exists($refReturnName)) { $cacheObjectKeys[$bindKey] = $refReturnName; } @@ -85,7 +87,7 @@ public function isBindable(object $object):bool { $bindKey = $this->getBindKey($refAttr); // TODO: Test for object type in object property. $attributeCache[$bindKey] - = fn(object $object, $key):null|iterable|string => $this->nullableStringOrIterable($object->$propName); + = fn(object $object, $key):null|iterable|string => $this->nullableStringOrIterable($object, $propName); } } elseif($refProp->isPublic()) { @@ -99,7 +101,7 @@ public function isBindable(object $object):bool { $attributeCache[$bindKey] = fn(object $object, $key):null|iterable|string => isset($object->$key) - ? $this->nullableStringOrIterable($object->$key) + ? $this->nullableStringOrIterable($object, $key) : null; if($refTypeName && class_exists($refTypeName)) { @@ -192,7 +194,10 @@ public function convertToKvp(object|array $object):array { $bindFunc = "get" . ucfirst($propName); if($objectToExtract) { if(property_exists($objectToExtract, $propName)) { - $objectToExtract = $objectToExtract->$propName; + try { + $objectToExtract = $objectToExtract->$propName; + } + catch(Error) {} } elseif(method_exists($objectToExtract, $bindFunc)) { $objectToExtract = $objectToExtract->$bindFunc(); @@ -249,7 +254,17 @@ private function getBindKey( } /** @return null|string|array */ - private function nullableStringOrIterable(mixed $value):null|iterable|string { + private function nullableStringOrIterable(object $object, string $keyOrMethod):null|iterable|string { + if(method_exists($object, $keyOrMethod)) { + $value = $object->$keyOrMethod(); + } + elseif(property_exists($object, $keyOrMethod)) { + $value = $object->$keyOrMethod; + } + else { + return null; + } + if(is_scalar($value)) { return $value; }