Passed
Push — master ( 59f55c...3e24bf )
by Daniel
06:16
created

FormSubmitHelper::process()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
nc 1
nop 3
dl 0
loc 9
ccs 0
cts 7
cp 0
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentsBundle\Helper\Form;
15
16
use Silverback\ApiComponentsBundle\Dto\FormView;
17
use Silverback\ApiComponentsBundle\Entity\Component\Form;
18
use Silverback\ApiComponentsBundle\Event\FormSuccessEvent;
19
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
20
use Symfony\Component\Form\FormFactoryInterface;
21
use Symfony\Component\Form\FormInterface;
22
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
23
24
/**
25
 * @author Daniel West <[email protected]>
26
 */
27
class FormSubmitHelper
28
{
29
    private FormFactoryInterface $formFactory;
30
    private EventDispatcherInterface $eventDispatcher;
31
32
    public function __construct(
33
        FormFactoryInterface $formFactory,
34
        EventDispatcherInterface $eventDispatcher
35
    ) {
36
        $this->formFactory = $formFactory;
37
        $this->eventDispatcher = $eventDispatcher;
38
    }
39
40
    public function process(Form $form, array $data, bool $isPartialSubmit): Form
41
    {
42
        $builder = $this->formFactory->createBuilder($form->formType);
43
        $symfonyForm = $builder->getForm();
44
        $formData = $this->getRootData($symfonyForm, $data);
45
        $symfonyForm->submit($formData, !$isPartialSubmit);
46
        $form->formView = new FormView($symfonyForm);
47
48
        return $form;
49
    }
50
51
    public function handleSuccess(Form $form)
52
    {
53
        $event = new FormSuccessEvent($form);
54
        $this->eventDispatcher->dispatch($event);
55
56
        return $event->result;
57
    }
58
59
    private function getRootData(FormInterface $form, $content): array
60
    {
61
        if (!isset($content[$form->getName()])) {
62
            throw new BadRequestHttpException(sprintf('Form object key could not be found. Expected: <b>%s</b>: { "input_name": "input_value" }', $form->getName()));
63
        }
64
65
        return $content[$form->getName()];
66
    }
67
}
68