2021-05-12 10:18:34 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Core\Twig\Extension;
|
|
|
|
|
2021-05-12 11:56:48 +02:00
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver;
|
2021-05-12 10:18:34 +02:00
|
|
|
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']]),
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
2021-05-13 17:49:19 +02:00
|
|
|
public function renderField($entity, array $config, ?string $locale = null): string
|
2021-05-12 10:18:34 +02:00
|
|
|
{
|
|
|
|
$field = $config['field'];
|
2021-05-12 11:56:48 +02:00
|
|
|
$instance = new $field();
|
2021-05-12 10:18:34 +02:00
|
|
|
$resolver = $instance->configureOptions(new OptionsResolver());
|
2021-06-16 20:00:35 +02:00
|
|
|
$flags = ENT_HTML5 | ENT_QUOTES;
|
2021-05-12 10:18:34 +02:00
|
|
|
|
2021-06-02 19:09:27 +02:00
|
|
|
$render = $instance->buildView($this->twig, $entity, $resolver->resolve($config['options']), $locale);
|
|
|
|
|
|
|
|
if (isset($config['options']['href'])) {
|
|
|
|
$hrefAttrConfig = $config['options']['href_attr'] ?? [];
|
|
|
|
$hrefConfig = $config['options']['href'] ?? null;
|
|
|
|
$attributes = '';
|
|
|
|
|
|
|
|
if (is_callable($hrefAttrConfig)) {
|
|
|
|
$attrs = (array) call_user_func($hrefAttrConfig, $entity, $config['options']);
|
|
|
|
} else {
|
|
|
|
$attrs = $hrefAttrConfig;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (is_callable($hrefConfig)) {
|
2021-06-03 13:51:20 +02:00
|
|
|
$attrs['href'] = call_user_func($hrefConfig, $entity, $config['options']);
|
2021-06-02 19:09:27 +02:00
|
|
|
} else {
|
2021-06-03 13:51:20 +02:00
|
|
|
$attrs['href'] = $hrefConfig;
|
2021-06-02 19:09:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
foreach ($attrs as $k => $v) {
|
2021-06-16 20:00:35 +02:00
|
|
|
$attributes .= sprintf(' %s="%s" ', htmlspecialchars($k, $flags), htmlspecialchars($v, $flags));
|
2021-06-02 19:09:27 +02:00
|
|
|
}
|
|
|
|
|
2021-06-03 13:51:20 +02:00
|
|
|
$render = sprintf('<a%s>%s</a>', $attributes, $render);
|
2021-06-02 19:09:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return $render;
|
2021-05-12 10:18:34 +02:00
|
|
|
}
|
|
|
|
}
|