add entity_to_array twig function

This commit is contained in:
Simon Vieille 2022-05-09 14:30:48 +02:00
parent 6bf65ccd2b
commit ff599a7101
Signed by: deblan
GPG Key ID: 579388D585F70417
1 changed files with 60 additions and 0 deletions

View File

@ -0,0 +1,60 @@
<?php
namespace App\Core\Twig\Extension;
use App\Core\Entity\EntityInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\MakerBundle\Str;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class EntityExtension extends AbstractExtension
{
protected PropertyAccessor $propertyAccessor;
public function __construct(EntityManagerInterface $entityManager)
{
$this->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;
}
}