Completed
Pull Request — master (#90)
by Arnaud
16:42
created

FormFactory   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 5
dl 0
loc 71
ccs 0
cts 19
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A create() 0 19 3
A guessForm() 0 17 2
1
<?php
2
3
namespace LAG\AdminBundle\Form\Factory;
4
5
use Exception;
6
use LAG\AdminBundle\Admin\AdminInterface;
7
use Symfony\Component\Form\FormFactoryInterface;
8
use Symfony\Component\Form\FormInterface;
9
10
// TODO class still useful ?
11
class FormFactory
12
{
13
    /**
14
     * @var FormFactoryInterface
15
     */
16
    protected $formFactory;
17
18
    /**
19
     * FormFactory constructor.
20
     *
21
     * @param FormFactoryInterface $formFactory
22
     */
23
    public function __construct(FormFactoryInterface $formFactory)
24
    {
25
        $this->formFactory = $formFactory;
26
    }
27
28
    /**
29
     * @param $formType
30
     * @param $entity
31
     * @param AdminInterface $admin
32
     *
33
     * @return FormInterface
34
     *
35
     * @throws Exception
36
     */
37
    public function create($formType, $entity, AdminInterface $admin)
38
    {
39
        // an valid entity should be passed
40
        if (!is_object($entity)) {
41
            throw new Exception('Invalid entity for form creation');
42
        }
43
44
        if (null === $formType) {
45
            $form = $this->guessForm($admin, $entity);
46
        } else {
47
            // a form type is defined, we use the form factory
48
            $form = $this
49
                ->formFactory
50
                ->create($formType, $entity)
51
            ;
52
        }
53
54
        return $form;
55
    }
56
57
    /**
58
     * Use Symfony's standard guesser to create the form type from the fields
59
     *
60
     * @param AdminInterface $admin
61
     * @param $entity
62
     * @return FormInterface
63
     */
64
    protected function guessForm(AdminInterface $admin, $entity)
65
    {
66
        $actionConfiguration = $admin
67
            ->getView()
68
            ->getConfiguration()
69
        ;
70
        $form = $this
71
            ->formFactory
72
            ->createNamed($admin->getName(), $entity)
73
        ;
74
75
        foreach ($actionConfiguration->getParameter('fields') as $field => $configuration) {
76
            $form->add($field, $configuration);
77
        }
78
79
        return $form;
80
    }
81
}
82