Completed
Push — master ( ac16a1...0cb3c4 )
by Dev
14:45
created

ConversationFormController::getFormManagerClass()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
c 0
b 0
f 0
nc 6
nop 1
dl 0
loc 14
rs 10
1
<?php
2
3
namespace PiedWeb\ConversationBundle\Controller;
4
5
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
6
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\HttpFoundation\Response;
9
use Symfony\Contracts\Translation\TranslatorInterface;
10
11
class ConversationFormController extends AbstractController
12
{
13
    private $translator;
14
15
    protected $form;
16
17
    /**
18
     * @var ParameterBagInterface
19
     */
20
    protected $params;
21
22
    public function __construct(
23
        TranslatorInterface $translator,
24
        ParameterBagInterface $params
25
    ) {
26
        $this->translator = $translator;
27
        $this->params = $params;
28
    }
29
30
    protected function getFormManagerClass($type)
31
    {
32
        $param = 'pwc.conversation.form'.($this->params->has('pwc.conversation.form.'.$type) ? '.'.$type : '_'.$type);
33
34
        if (!$this->params->has($param)) {
35
            throw new \Exception('`'.$type.'` does\'nt exist (not configured).');
36
        }
37
38
        $class = $this->params->get($param);
39
        if (!class_exists($class)) {
40
            throw new \Exception('`'.$type.'` does\'nt exist.');
41
        }
42
43
        return $class;
44
    }
45
46
    /**
47
     * Return current form manager depending on `type` (request).
48
     */
49
    protected function getFormManager(string $type, Request $request)
50
    {
51
        if (null !== $this->form) {
52
            return $this->form;
53
        }
54
55
        $class = $this->getFormManagerClass($type);
56
57
        return $this->form = new $class(
58
            $this->params->get('pwc.conversation.entity_message'),
59
            $request,
60
            $this->get('doctrine'),
61
            $this->get('security.token_storage'),
62
            $this->get('form.factory'),
63
            $this->get('twig'),
64
            $this->get('router'),
65
            $this->get('translator')
66
        );
67
    }
68
69
    public function show(string $type, Request $request)
70
    {
71
        $response = new Response();
72
73
        $form = $this->getFormManager($type, $request)->getCurrentStep()->getForm();
74
        $form->handleRequest($request);
75
76
        if ($form->isSubmitted()) {
77
            return $response->setContent($this->getFormManager($type, $request)->validCurrentStep($form));
78
        }
79
80
        return $response->setContent($this->getFormManager($type, $request)->showForm($form));
81
    }
82
}
83