From bb6ca7da07eec819e7876bcb0e25f0d7c87d5f30 Mon Sep 17 00:00:00 2001 From: Philipp Dieter Date: Mon, 5 Jul 2021 14:24:41 +0200 Subject: [PATCH] [TASK] Extend object from array mapping for nested and related objects --- Classes/Utility/ObjectUtility.php | 61 ++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/Classes/Utility/ObjectUtility.php b/Classes/Utility/ObjectUtility.php index ec4496a..4cfaa03 100644 --- a/Classes/Utility/ObjectUtility.php +++ b/Classes/Utility/ObjectUtility.php @@ -12,6 +12,11 @@ namespace Cjel\TemplatesAide\Utility; * ***/ +use Cjel\TemplatesAide\Utility\ObjectUtility; +use TYPO3\CMS\Core\Utility\GeneralUtility; +use TYPO3\CMS\Extbase\Object\ObjectManager; +use TYPO3\CMS\Extbase\Persistence\ObjectStorage; + /** * */ @@ -22,9 +27,61 @@ class ObjectUtility * * @return void */ - public static function fromArray(&$object, $data) { + public static function fromArray( + &$object, $data, $storageMapping = [] + ) { + $objectManager = GeneralUtility::makeInstance( + ObjectManager::class + ); + $reflectionClass = new \ReflectionClass(get_class($object)); foreach ($data as $property => $value) { - $object->_setProperty($property, $value); + $methodName = 'set' . ucfirst($property); + if (!$reflectionClass->hasMethod($methodName)) { + continue; + } + $method = $reflectionClass->getMethod($methodName); + $params = $method->getParameters(); + $methodType = $params[0]->getType(); + if (is_array($value)) { + if (array_key_exists($property, $storageMapping)) { + $storage = $object->_getProperty($property); + $storageUpdated = $objectManager->get( + ObjectStorage::class + ); + foreach ($value as $row) { + $item = null; + if ($row['uid']) { + foreach ($storage as $storageIitem) { + if ($storageIitem->getUid() == $row['uid']) { + $item = $storageIitem; + } + } + $storageUpdated->attach($item); + } + if (!$item) { + $item = new $storageMapping[$property](); + $storageUpdated->attach($item); + } + self::fromArray($item, $row); + } + $object->_setProperty($property, $storageUpdated); + } + } else { + if ($methodType == null) { + $value = StringUtility::checkAndfixUtf8($value); + $object->_setProperty($property, $value); + } else { + $typeParts = explode('\\', (string)$methodType); + $typeParts[count($typeParts) - 2] = 'Repository'; + $repositoryClass = join('\\', $typeParts); + $repositoryClass .= 'Repository'; + if (class_exists($repositoryClass)) { + $repository = $objectManager->get($repositoryClass); + $relatedObject = $repository->findByUid($value); + $object->_setProperty($property, $relatedObject); + } + } + } } } }