Completed
Pull Request — master (#90)
by Arnaud
02:15
created

FormFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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 1
    public function __construct(FormFactoryInterface $formFactory)
23
    {
24 1
        $this->formFactory = $formFactory;
25 1
    }
26
27
    /**
28
     * @param $formType
29
     * @param $entity
30
     * @param AdminInterface $admin
31
     *
32
     * @return FormInterface
33
     *
34
     * @throws Exception
35
     */
36 1
    public function create($formType, $entity, AdminInterface $admin)
37
    {
38
        // an valid entity should be passed
39 1
        if (!is_object($entity)) {
40 1
            throw new Exception('Invalid entity for form creation');
41
        }
42
43 1
        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 1
                ->formFactory
49 1
                ->create($formType, $entity);
50
        }
51
52 1
        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
        $actionConfiguration = $admin
65
            ->getView()
66
            ->getConfiguration()
67
        ;
68
        $form = $this
69
            ->formFactory
70
            ->createNamed($admin->getName(), $entity)
71
        ;
72
73
        foreach ($actionConfiguration->getParameter('fields') as $field => $configuration) {
74
            $form->add($field);
75
        }
76
77
        return $form;
78
    }
79
}
80