<?php namespace App\Controller; use App\Form\AbstractFormManager; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\FormFactory; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Stopwatch\Stopwatch; /** * Abstract class for generic controller */ abstract class AbstractExtendedController extends AbstractController { /** @var Stopwatch Profiler stopwatch */ protected $stopwatch = null; public function __construct(Stopwatch $stopwatch) { $this->stopwatch = $stopwatch; } /** * Create the json answer for an ajax form * - code : Http code * - error : Form error content * - message : A popup message to display * - redirect : Redirect the user to a specific URL * - refresh : Refresh the page * - reset : Reset the form * * @param array $settings * @return JsonResponse */ protected function ajaxFormAnswer(array $settings = []): JsonResponse { $data = [ "message" => $settings["message"] ?? "", "redirect" => $settings["redirect"] ?? "", "error" => $settings["error"] ?? "", "refresh" => $settings["refresh"] ?? false, "reset" => $settings["reset"] ?? false, ]; return $this->json($data, $settings["code"] ?? Response::HTTP_OK); } /** * Create a form inherited from AbstractGenericForm * * @param string $name * @param string $type * @param array $options * @return AbstractFormManager */ protected function createNamedCustomForm(string $name, string $type, array $options = []): AbstractFormManager { $this->stopwatch->start($name, 'form'); /** @var FormFactory $formFactory */ $formFactory = $this->container->get('form.factory'); $formBuilder = $formFactory->createNamedBuilder($name, FormType::class); $this->stopwatch->stop($name); return new $type($formBuilder, $options, true); } /** * Create a form inherited from AbstractGenericForm with get method * * @param string $name * @param string $type * @param array $options * @return AbstractFormManager */ protected function createNamedGetCustomForm(string $name, string $type, array $options = []): AbstractFormManager { $this->stopwatch->start($name, 'form'); /** @var FormFactory $formFactory */ $formFactory = $this->container->get('form.factory'); $formBuilder = $formFactory->createNamedBuilder($name, FormType::class, [], [ 'csrf_protection' => false, ]); $formBuilder->setMethod('GET'); $this->stopwatch->stop($name); return new $type($formBuilder, $options, false); } }