Passed
Push — feature/uploadable ( 7c6d25...a7ed20 )
by Daniel
11:07
created

FormSubmitHandler::isAssocArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
ccs 0
cts 4
cp 0
crap 6
rs 10
c 0
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\Form\Handler;
15
16
use Silverback\ApiComponentsBundle\Dto\FormView;
17
use Silverback\ApiComponentsBundle\Entity\Component\Form;
18
use Silverback\ApiComponentsBundle\Event\FormSuccessEvent;
19
use Silverback\ApiComponentsBundle\Factory\Form\FormFactory;
20
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
21
use Symfony\Component\Form\FormInterface;
22
use Symfony\Component\HttpFoundation\Response;
23
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
24
use Symfony\Component\Serializer\SerializerInterface;
25
26
/**
27
 * @author Daniel West <[email protected]>
28
 */
29
class FormSubmitHandler
30
{
31
    private FormFactory $formFactory;
32
    private EventDispatcherInterface $eventDispatcher;
33
    private SerializerInterface $serializer;
34
35
    public function __construct(FormFactory $formFactory, EventDispatcherInterface $eventDispatcher, SerializerInterface $serializer)
36
    {
37
        $this->formFactory = $formFactory;
38
        $this->eventDispatcher = $eventDispatcher;
39
        $this->serializer = $serializer;
40
    }
41
42
    public function handle(array $decodedContent, bool $isPatchRequest, Form $formResource, string $_format): Response
43
    {
44
        $builder = $this->formFactory->create($formResource);
45
        $form = $builder->getForm();
46
        $formData = $this->validateDecodedContent($form, $decodedContent);
47
        $form->submit($formData, !$isPatchRequest);
48
        if ($isPatchRequest) {
49
            return $this->handlePatch($formResource, $form, $_format, $formData);
50
        }
51
52
        return $this->handlePost($formResource, $form, $_format);
53
    }
54
55
    private function handlePost(Form $formResource, FormInterface $form, string $_format): Response
56
    {
57
        $valid = $form->isValid();
58
        $formResource->formView = new FormView($form);
59
        $context = [];
60
        $response = $formResource;
61
        if ($valid) {
62
            $event = new FormSuccessEvent($formResource, $form, $response);
63
            $this->eventDispatcher->dispatch($event);
64
            $response = $event->response;
65
            $context = $event->serializerContext;
66
        }
67
68
        return $this->getResponse($response, $_format, $valid, $context);
69
    }
70
71
    private function handlePatch(Form $formResource, FormInterface $form, string $_format, array $formData): Response
72
    {
73
        $dataCount = \count($formData);
74
        if (!$dataCount) {
75
            return $this->getResponse($formResource, $_format, true);
76
        }
77
78
        if (1 === $dataCount) {
79
            $formData = [$formData];
80
        }
81
82
        return $this->getPatchValidationResponse($formResource, $form, $_format, $formData);
83
    }
84
85
    private function getPatchValidationResponse(Form $formResource, FormInterface $form, string $_format, array $formData): Response
86
    {
87
        $formResources = [];
88
        $valid = true;
89
        foreach ($formData as $key => $value) {
90
            $dataItem = clone $formResource;
91
            $data = \is_string($formData[$key]) ? [$key => $formData[$key]] : $formData[$key];
92
            $formItem = $this->getChildFormByKey($form, $data);
93
            $dataItem->formView = $formView = new FormView($formItem);
94
            $formResources[] = $dataItem;
95
            if ($valid && !self::isFormViewValid($formView)) {
96
                $valid = false;
97
            }
98
        }
99
100
        return $this->getResponse($formResources, $_format, $valid);
101
    }
102
103
    private static function isFormViewValid(FormView $formView): bool
104
    {
105
        return $formView->getVars()['valid'];
106
    }
107
108
    private function validateDecodedContent(FormInterface $form, $content): array
109
    {
110
        if (!isset($content[$form->getName()])) {
111
            throw new BadRequestHttpException(sprintf('Form object key could not be found. Expected: <b>%s</b>: { "input_name": "input_value" }', $form->getName()));
112
        }
113
114
        return $content[$form->getName()];
115
    }
116
117
    private function getChildFormByKey(FormInterface $form, array $formData): FormInterface
118
    {
119
        $child = $form->get($key = key($formData));
0 ignored issues
show
Bug introduced by
It seems like $key = key($formData) can also be of type null; however, parameter $name of Symfony\Component\Form\FormInterface::get() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

119
        $child = $form->get(/** @scrutinizer ignore-type */ $key = key($formData));
Loading history...
120
        while ($this->isSequentialStringsArray($formData = $formData[$key]) && $count = \count($formData)) {
121
            if (1 === $count) {
122
                $child = $child->get((string) $key = key($formData));
123
                continue;
124
            }
125
            // front-end should submit empty objects for each item in a collection up to the one we are trying to validate
126
            // so let us just get the last item to validate
127
            // key should be numeric, if not it is probably first and second for repeated field. These should both be checked...
128
            $key = (string) ($count - 1);
129
            if (!$child->has($key)) {
130
                break;
131
            }
132
            $child = $child->get($key);
133
        }
134
135
        return $child;
136
    }
137
138
    private function isSequentialStringsArray($data): bool
139
    {
140
        return \is_array($data) && !$this->isAssocArray($data) && $this->arrayIsStrings($data);
141
    }
142
143
    private function isAssocArray(array $arr): bool
144
    {
145
        if ([] === $arr) {
146
            return false;
147
        }
148
149
        return array_keys($arr) !== range(0, \count($arr) - 1);
150
    }
151
152
    private function arrayIsStrings(array $arr): bool
153
    {
154
        foreach ($arr as $item) {
155
            if (!\is_string($item)) {
156
                return false;
157
            }
158
        }
159
160
        return true;
161
    }
162
163
    private function getResponse(
164
        $data,
165
        string $_format,
166
        bool $valid,
167
        array $context = []
168
    ): Response {
169
        $response = new Response();
170
        $response->setStatusCode($valid ? Response::HTTP_OK : Response::HTTP_BAD_REQUEST);
171
        $response->setContent($this->serializer->serialize($data, $_format, $context));
172
173
        return $response;
174
    }
175
}
176