From f15bc5c3ea601568ee4853e9c34f362003993918 Mon Sep 17 00:00:00 2001 From: Christian Bieg Date: Wed, 13 May 2020 17:04:02 +0200 Subject: [PATCH] Added the ability to convert documents from an inherited index class --- Mapping/Converter.php | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/Mapping/Converter.php b/Mapping/Converter.php index 6778c0f6..eabed66f 100644 --- a/Mapping/Converter.php +++ b/Mapping/Converter.php @@ -36,18 +36,32 @@ public function convertArrayToDocument(string $namespace, array $raw) public function convertDocumentToArray($document): array { - $class = get_class($document); + $documentClass = get_class($document); + $class = $this->getConvertableClass($documentClass); - if (!isset($this->propertyMetadata[$class])) { - throw new \Exception("Cannot convert object of class `$class` to array."); + if ($class !== null) { + return $this->normalize($document, null, $class); } - return $this->normalize($document); + throw new \Exception("Cannot convert object of class `$documentClass` to array."); } - protected function normalize($document, $metadata = null) + public function getConvertableClass($class) { + while ($class) { + if (isset($this->propertyMetadata[$class])) { + return $class; + } + + $class = get_parent_class($class); + } + + return null; + } + + protected function normalize($document, $metadata = null, $class = null) { - $metadata = $metadata ?? $this->propertyMetadata[get_class($document)]; + $class = $class ?? get_class($document); + $metadata = $metadata ?? $this->propertyMetadata[$class]; $result = []; foreach ($metadata as $field => $fieldMeta) {