Completed
Pull Request — dev (#48)
by Arnaud
29:13 queued 01:23
created

FormFactory::create()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 18
rs 9.4285
cc 3
eloc 10
nc 3
nop 3
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
class FormFactory
11
{
12
    /**
13
     * @var FormFactoryInterface
14
     */
15
    protected $formFactory;
16
17
    /**
18
     * FormFactory constructor.
19
     *
20
     * @param FormFactoryInterface $formFactory
21
     */
22
    public function __construct(FormFactoryInterface $formFactory)
23
    {
24
        $this->formFactory = $formFactory;
25
    }
26
27
    /**
28
     * @param $formType
29
     * @param $entity
30
     * @param AdminInterface $admin
31
     *
32
     * @return FormInterface
33
     *
34
     * @throws Exception
35
     */
36
    public function create($formType, $entity, AdminInterface $admin)
37
    {
38
        // an valid entity should be passed
39
        if (!is_object($entity)) {
40
            throw new Exception('Invalid entity for form creation');
41
        }
42
43
        if (null === $formType) {
44
            $form = $this->guessForm($admin, $entity);
45
        } else {
46
            // a form type is defined, we use the form factory
47
            $form = $this
48
                ->formFactory
49
                ->create($formType, $entity);
50
        }
51
52
        return $form;
53
    }
54
55
    /**
56
     * Use Symfony's standard guesser to create the form type from the fields
57
     *
58
     * @param AdminInterface $admin
59
     * @param $entity
60
     * @return FormInterface
61
     */
62
    protected function guessForm(AdminInterface $admin, $entity)
63
    {
64
        $action = $admin->getCurrentAction();
65
        $form = $this
66
            ->formFactory
67
            ->createNamed($admin->getName(), $entity);
68
69
        foreach ($action->getFields() as $field) {
70
            $form->add($field->getName());
71
        }
72
73
        return $form;
74
    }
75
}
76