58 lines
1.7 KiB
PHP
58 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Core\Twig\Extension;
|
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver;
|
|
use Symfony\Component\PropertyAccess\PropertyAccess;
|
|
use Symfony\Component\PropertyAccess\PropertyAccessor;
|
|
use Twig\Environment;
|
|
use Twig\Extension\AbstractExtension;
|
|
use Twig\TwigFunction;
|
|
|
|
class CrudExtension extends AbstractExtension
|
|
{
|
|
protected PropertyAccessor $propertyAccessor;
|
|
protected Environment $twig;
|
|
|
|
public function __construct(Environment $twig)
|
|
{
|
|
$this->propertyAccessor = PropertyAccess::createPropertyAccessorBuilder()
|
|
->getPropertyAccessor()
|
|
;
|
|
|
|
$this->twig = $twig;
|
|
}
|
|
|
|
/**
|
|
* {@inheritdoc}
|
|
*/
|
|
public function getFunctions()
|
|
{
|
|
return [
|
|
new TwigFunction('render_field', [$this, 'renderField'], ['is_safe' => ['html']]),
|
|
];
|
|
}
|
|
|
|
public function renderField($entity, array $config, ?string $locale = null): string
|
|
{
|
|
$field = $config['field'];
|
|
$instance = new $field();
|
|
$resolver = $instance->configureOptions(new OptionsResolver());
|
|
|
|
$render = $instance->buildView($this->twig, $entity, $resolver->resolve($config['options']), $locale);
|
|
|
|
if (isset($config['options']['href'])) {
|
|
$config['options']['href_attr'] = $config['options']['href_attr'] ?? [];
|
|
$attributes = '';
|
|
|
|
foreach ($config['options']['href_attr'] as $k => $v) {
|
|
$attributes .= sprintf('%s="%s" ', htmlspecialchars($k), htmlspecialchars($v));
|
|
}
|
|
|
|
$render = sprintf('<a href="%s" %s>%s</a>', htmlspecialchars($config['options']['href']), $attributes, $render);
|
|
}
|
|
|
|
return $render;
|
|
}
|
|
}
|