Passed
Pull Request — master (#66)
by Daniel
10:32 queued 04:22
created

FormSubmitHelper   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
dl 0
loc 31
ccs 0
cts 15
cp 0
rs 10
c 1
b 0
f 0
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 9 1
A __construct() 0 6 1
A getRootData() 0 7 2
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 Symfony\Component\EventDispatcher\EventDispatcherInterface;
19
use Symfony\Component\Form\FormFactoryInterface;
20
use Symfony\Component\Form\FormInterface;
21
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
22
23
/**
24
 * @author Daniel West <[email protected]>
25
 */
26
class FormSubmitHelper
27
{
28
    private FormFactoryInterface $formFactory;
29
    private EventDispatcherInterface $eventDispatcher;
30
31
    public function __construct(
32
        FormFactoryInterface $formFactory,
33
        EventDispatcherInterface $eventDispatcher
34
    ) {
35
        $this->formFactory = $formFactory;
36
        $this->eventDispatcher = $eventDispatcher;
37
    }
38
39
    public function process(Form $form, array $data, bool $isPartialSubmit): Form
40
    {
41
        $builder = $this->formFactory->createBuilder($form->formType);
42
        $symfonyForm = $builder->getForm();
43
        $formData = $this->getRootData($symfonyForm, $data);
44
        $symfonyForm->submit($formData, !$isPartialSubmit);
45
        $form->formView = new FormView($symfonyForm);
46
47
        return $form;
48
    }
49
50
    private function getRootData(FormInterface $form, $content): array
51
    {
52
        if (!isset($content[$form->getName()])) {
53
            throw new BadRequestHttpException(sprintf('Form object key could not be found. Expected: <b>%s</b>: { "input_name": "input_value" }', $form->getName()));
54
        }
55
56
        return $content[$form->getName()];
57
    }
58
}
59