Completed
Pull Request — master (#90)
by Arnaud
05:26
created

CreateFormHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 2
1
<?php
2
3
namespace LAG\AdminBundle\Form\Handler;
4
5
use LAG\AdminBundle\Admin\AdminInterface;
6
use Symfony\Bundle\FrameworkBundle\Routing\Router;
7
use Symfony\Component\Form\ClickableInterface;
8
use Symfony\Component\Form\FormInterface;
9
use Symfony\Component\HttpFoundation\RedirectResponse;
10
use Symfony\Component\HttpFoundation\Response;
11
use Twig_Environment;
12
13
/**
14
 * Create a response from the form data.
15
 */
16
class CreateFormHandler implements FormHandlerInterface
17
{
18
    /**
19
     * @var Twig_Environment
20
     */
21
    private $twig;
22
    
23
    /**
24
     * @var Router
25
     */
26
    private $router;
27
    
28
    /**
29
     * EditFormHandler constructor.
30
     *
31
     * @param Twig_Environment $twig
32
     * @param Router $router
33
     */
34
    public function __construct(Twig_Environment $twig, Router $router)
35
    {
36
        $this->twig = $twig;
37
        $this->router = $router;
38
    }
39
    
40
    /**
41
     * Save the entity if the form is valid, and redirect to the list action if
42
     * required
43
     *
44
     * @param FormInterface $form
45
     * @param AdminInterface $admin
46
     *
47
     * @return RedirectResponse|Response
48
     */
49
    public function handle(FormInterface $form, AdminInterface $admin)
50
    {
51
        $template = $admin
52
            ->getCurrentAction()
53
            ->getConfiguration()
54
            ->getParameter('template')
55
        ;
56
        
57
        if ($form->isValid()) {
58
            // if the form is valid, we save the entity
59
            $admin->create();
60
    
61
            /** @var ClickableInterface $input */
62
            $input = $form->get('save-and-redirect');
63
    
64
            if ($input->isClicked() && $admin->hasAction('list')) {
65
                // if the redirect input is clicked and the list action exists, we redirect to the list action
66
                $url = $this
67
                    ->router
68
                    ->generate($admin->generateRouteName('list'));
69
                
70
                return new RedirectResponse($url);
71
            }
72
        }
73
        // display the form after validation or not
74
        $content = $this
75
            ->twig
76
            ->render($template, [
77
                'admin' => $admin,
78
                'form' => $form->createView()
79
            ])
80
        ;
81
    
82
        return new Response($content);
83
    }
84
}
85