<?php
declare(strict_types=1);
namespace App\Twig\Functions;
use Symfony\Component\Form\FormFactoryInterface;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* Extension for showing forms globally
*
* @package App\Twig\Functions
*/
class FormExtension extends AbstractExtension
{
private FormFactoryInterface $formFactory;
/**
* FormExtension constructor.
*
* @param FormFactoryInterface $formFactory
*/
public function __construct(FormFactoryInterface $formFactory)
{
$this->formFactory = $formFactory;
}
/**
* Create empty form
*
* @param Environment $twig
* @param string $formName
* @param string $template
*
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*
* @return string
*/
public function createForm(Environment $twig, string $formName, string $template): string
{
return $twig->render($template, ['form' => $this->formFactory->create($formName)->createView()]);
}
/**
* Get twig functions
*
* @return array
*/
public function getFunctions(): array
{
return [
new TwigFunction(
'create_form',
[
$this, 'createForm'
],
[
'is_safe' => ['html'],
'needs_environment' => true
]
),
];
}
}