Test Failed
Push — develop ( f6d190...8ff4ed )
by Daniel
04:04
created

FormPostAction   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 51
rs 10
c 0
b 0
f 0
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
B __invoke() 0 22 7
1
<?php
2
3
namespace Silverback\ApiComponentBundle\Controller;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use Silverback\ApiComponentBundle\Entity\Component\Form\Form;
7
use Silverback\ApiComponentBundle\DTO\Form\FormView;
8
use Silverback\ApiComponentBundle\Factory\Form\FormFactory;
9
use Silverback\ApiComponentBundle\Form\Handler\FormHandlerInterface;
10
use Silverback\ApiComponentBundle\Validator\ClassNameValidator;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpFoundation\Response;
13
use Symfony\Component\Serializer\SerializerInterface;
14
15
class FormPostAction extends AbstractFormAction
16
{
17
    /**
18
     * @var iterable|FormHandlerInterface[]
19
     */
20
    private $handlers;
21
22
    public function __construct(
23
        EntityManagerInterface $entityManager,
24
        SerializerInterface $serializer,
25
        FormFactory $formFactory,
26
        iterable $formHandlers
27
    ) {
28
        parent::__construct($entityManager, $serializer, $formFactory);
29
        $this->handlers = $formHandlers;
30
    }
31
32
    /**
33
     * @param Request $request
34
     * @param Form $data
35
     * @return Response
36
     * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
37
     * @throws \Symfony\Component\Form\Exception\AlreadySubmittedException
38
     * @throws \UnexpectedValueException
39
     * @throws \InvalidArgumentException
40
     * @throws \Symfony\Component\Form\Exception\LogicException
41
     * @throws \BadMethodCallException
42
     * @throws \LogicException
43
     */
44
    public function __invoke(Request $request, Form $data)
45
    {
46
        $contentType = $request->headers->get('CONTENT_TYPE');
47
        $_format = $request->attributes->get('_format') ?: $request->getFormat($contentType);
48
49
        $form = $this->formFactory->create($data);
50
        $formData = $this->deserializeFormData($form, $request->getContent());
51
        $form->submit($formData);
52
        if (!$form->isSubmitted()) {
53
            return $this->getResponse($data, $_format, false);
54
        }
55
        $valid = $form->isValid();
56
        $data->setForm(new FormView($form->createView()));
57
        if ($valid && $data->getSuccessHandler()) {
58
            foreach ($this->handlers as $handler) {
59
                if (ClassNameValidator::isClassSame($data->getSuccessHandler(), $handler)) {
60
                    $handler->success($data);
61
                    break;
62
                }
63
            }
64
        }
65
        return $this->getResponse($data, $_format, $valid);
66
    }
67
}
68