Skip to content

Instantly share code, notes, and snippets.

@ollo-ride-nico
Created February 9, 2019 16:15
Show Gist options
  • Save ollo-ride-nico/7e629f3746a0c2fb5f43db08f231a400 to your computer and use it in GitHub Desktop.
Save ollo-ride-nico/7e629f3746a0c2fb5f43db08f231a400 to your computer and use it in GitHub Desktop.
abstract class Handler
{
protected $form;
protected $formFactory;
protected $data;
protected $request;
protected $router;
protected $twig;
protected $flashBag;
public function __construct(Form $form, Request $request, FormFactory $formFactory, RouterInterface $router, Environment $twig, FlashBagInterface $flashBag)
{
$this->form = $form;
$this->formFactory = $formFactory;
$this->request = $request;
$this->router = $router;
$this->twig =$twig;
$this->flashBag =$flashBag;
}
public function onCreate(): FormInterface
{
$this->form = $this->formFactory->create($this->getFormType(), $this->data, $this->getFormOptions());
return $this->form;
}
public function handle($data = null, $request)
{
$this->data = $data;
$this->request = $request;
$this->onCreate()->handleRequest($request);
if ($this->form->isSubmitted() && $this->form->isValid()) {
return true;
}
return false;
}
public function getFormOptions(): array
{
return [];
}
public abstract static function getFormType(): string;
public function createTask(
Request $request,
Security $security,
FormFactory $formFactory,
Session $session,
RouterInterface $router,
TaskHandler $taskHandler
): Response {
$taskHandler->handle(new Task(), $request);
// On récupère l 'utilisateur de la session
$user = $security->getUser();
if ($taskHandler->onSuccess()){
// On attribut le 'username' de la session à la tache créée
//$task->setUser($user);
$session->getFlashBag()->add('success', 'La tâche a été bien été ajoutée.');
return new RedirectResponse($router->generate('task_list'));
}
return new Response($this->twig->render(
'task/create.html.twig',
['form' => $taskHandler->onCreate()->createView()]
));
}
class TaskHandler extends Handler
{
private $entityManager;
public function __construct(
Form $form,
Request $request,
FormFactory $formFactory,
RouterInterface $router,
Environment $twig,
FlashBagInterface $flashBag,
EntityManager $entityManager
) {
parent::__construct($form, $request, $formFactory, $router, $twig, $flashBag);
$this->entityManager = $entityManager;
}
public static function getFormType(): string
{
return TaskType::class;
}
public function onSuccess(): Response
{
$task = $this->form->getData();
$this->entityManager->persist($task);
$this->entityManager->flush();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment