Completed
Push — master ( 0f15f1...06dce9 )
by Pavel
09:44
created

MappedEntityFormFactory::createFormForClass()   B

Complexity

Conditions 3
Paths 5

Size

Total Lines 35
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 3.2621

Importance

Changes 0
Metric Value
dl 0
loc 35
ccs 18
cts 26
cp 0.6923
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 22
nc 5
nop 1
crap 3.2621
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 3
    public function __construct(FormFactoryInterface $factory, PropertyMapperInterface $mapper)
25
    {
26 3
        $this->factory = $factory;
27 3
        $this->mapper  = $mapper;
28 3
    }
29
30
    /**
31
     * @param $className
32
     *
33
     * @return FormInterface
34
     *
35
     * @throws EntityProcessingException
36
     */
37 3
    public function createFormForClass($className)
38
    {
39 3
        $form = $this->factory->create(
40 3
            FormType::class,
41 3
            null,
42
            [
43 3
                'data_class' => $className,
44
            ]
45 3
        );
46
47
        try {
48 3
            foreach ($this->mapper->getApiProperties($className) as $apiProperty) {
49 3
                $form->add(
50 3
                    $this->factory->createForProperty(
51 3
                        $className,
52 3
                        $this->mapper->getEntityProperty($className, $apiProperty),
53 3
                        null,
54 3
                        ['auto_initialize' => false]
55 3
                    )
56 3
                );
57 3
            }
58 3
        } 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 3
        return $form;
71
    }
72
}
73