From 4e27bf21864be1514391d22ef08e2df855169a51 Mon Sep 17 00:00:00 2001 From: Ian Foulds Date: Sun, 1 Oct 2023 17:39:49 +0100 Subject: [PATCH] Fix for RFC #114 - Recursively add parent properties if specified. --- src/ReflectionHydrator.php | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/ReflectionHydrator.php b/src/ReflectionHydrator.php index 9718743..e64e96e 100644 --- a/src/ReflectionHydrator.php +++ b/src/ReflectionHydrator.php @@ -21,10 +21,10 @@ class ReflectionHydrator extends AbstractHydrator * * {@inheritDoc} */ - public function extract(object $object): array + public function extract(object $object, bool $includeParentProperties = false): array { $result = []; - foreach (self::getReflProperties($object) as $property) { + foreach (self::getReflProperties($object, $includeParentProperties) as $property) { $propertyName = $this->extractName($property->getName(), $object); if (! $this->getCompositeFilter()->filter($propertyName)) { continue; @@ -42,9 +42,9 @@ public function extract(object $object): array * * {@inheritDoc} */ - public function hydrate(array $data, object $object) + public function hydrate(array $data, object $object, bool $includeParentProperties = false) { - $reflProperties = self::getReflProperties($object); + $reflProperties = self::getReflProperties($object, $includeParentProperties); foreach ($data as $key => $value) { $name = $this->hydrateName($key, $data); if (isset($reflProperties[$name])) { @@ -60,21 +60,23 @@ public function hydrate(array $data, object $object) * * @return ReflectionProperty[] */ - protected static function getReflProperties(object $input): array + protected static function getReflProperties(object $input, bool $includeParentProperties): array { - $class = $input::class; + $class = get_class($input); if (isset(static::$reflProperties[$class])) { return static::$reflProperties[$class]; } static::$reflProperties[$class] = []; - $reflClass = new ReflectionClass($class); - $reflProperties = $reflClass->getProperties(); + $reflClass = new ReflectionClass($class); - foreach ($reflProperties as $property) { - static::$reflProperties[$class][$property->getName()] = $property; - } + do { + foreach ($reflClass->getProperties() as $property) { + $property->setAccessible(true); + static::$reflProperties[$class][$property->getName()] = $property; + } + } while ($includeParentProperties === true && ($reflClass = $reflClass->getParentClass()) !== false); return static::$reflProperties[$class]; }