Completed
Pull Request — master (#21)
by Pavel
21:56
created

MappedEntityFormFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
namespace ScayTrase\Api\Cruds\Adaptors\Symfony;
4
5
use ScayTrase\Api\Cruds\Exception\EntityProcessingException;
6
use ScayTrase\Api\Cruds\PropertyMapperInterface;
7
use Symfony\Component\Form\Extension\Core\Type\FormType;
8
use Symfony\Component\Form\FormFactoryInterface;
9
use Symfony\Component\Form\FormInterface;
10
11
final class MappedEntityFormFactory
12
{
13
    /** @var  FormFactoryInterface */
14
    private $factory;
15
    /** @var  PropertyMapperInterface */
16
    private $mapper;
17
18
    /**
19
     * MappedEntityFormFactory constructor.
20
     *
21
     * @param FormFactoryInterface    $factory
22
     * @param PropertyMapperInterface $mapper
23
     */
24 6
    public function __construct(FormFactoryInterface $factory, PropertyMapperInterface $mapper)
25
    {
26 6
        $this->factory = $factory;
27 6
        $this->mapper  = $mapper;
28 6
    }
29
30
    /**
31
     * @param $className
32
     *
33
     * @return FormInterface
34
     *
35
     * @throws EntityProcessingException
36
     */
37 6
    public function createFormForClass($className)
38
    {
39 6
        $form = $this->factory->create(
40 6
            FormType::class,
41 6
            null,
42
            [
43 6
                'data_class' => $className,
44
            ]
45
        );
46
47
        try {
48 6
            foreach ($this->mapper->getApiProperties($className) as $apiProperty) {
49 6
                $form->add(
50 6
                    $this->factory->createForProperty(
51 6
                        $className,
52 6
                        $this->mapper->getEntityProperty($className, $apiProperty),
53 6
                        null,
54 6
                        ['auto_initialize' => false]
55
                    )
56
                );
57
            }
58
        } catch (\Exception $exception) {
59
            throw new EntityProcessingException(
60
                sprintf(
61
                    'Cannot create form for class %s: %s',
62
                    $className,
63
                    $exception->getMessage()
64
                ),
65
                $exception->getCode(),
66
                $exception
67
            );
68
        }
69
70 6
        return $form;
71
    }
72
}
73