From ff599a71011558f7ec09a4a1af4c8f159dfd6db8 Mon Sep 17 00:00:00 2001 From: Simon Vieille Date: Mon, 9 May 2022 14:30:48 +0200 Subject: [PATCH] add entity_to_array twig function --- src/core/Twig/Extension/EntityExtension.php | 60 +++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/core/Twig/Extension/EntityExtension.php diff --git a/src/core/Twig/Extension/EntityExtension.php b/src/core/Twig/Extension/EntityExtension.php new file mode 100644 index 0000000..466cf79 --- /dev/null +++ b/src/core/Twig/Extension/EntityExtension.php @@ -0,0 +1,60 @@ +entityManager = $entityManager; + $this->propertyAccessor = PropertyAccess::createPropertyAccessorBuilder() + ->disableExceptionOnInvalidPropertyPath() + ->getPropertyAccessor() + ; + } + + /** + * {@inheritdoc} + */ + public function getFunctions() + { + return [ + new TwigFunction('entity_to_array', [$this, 'toArray']), + ]; + } + + public function toArray(EntityInterface $entity): array + { + $metaData = $this->entityManager->getClassMetadata(get_class($entity)); + $array = []; + + foreach ($metaData->fieldNames as $field) { + try { + $value = $this->propertyAccessor->getValue($entity, $field); + + if (is_object($value)) { + $value = (string) $value; + } + + $array[$field] = [ + 'id' => $field, + 'name' => Str::asHumanWords($field), + 'value' => $value, + ]; + } catch (\Error $e) { + } + } + + return $array; + } +}