Passed
Push — v2 ( 8dd6b3...97d08f )
by Daniel
06:52
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 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 0
cts 4
cp 0
crap 6
rs 10
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component 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\ApiComponentBundle\Form\Handler;
15
16
use Silverback\ApiComponentBundle\Dto\FormView;
17
use Silverback\ApiComponentBundle\Entity\Component\Form;
18
use Silverback\ApiComponentBundle\Event\FormSuccessEvent;
19
use Silverback\ApiComponentBundle\Factory\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 handlePatch(Form $formResource, FormInterface $form, string $_format, array $formData): Response
56
    {
57
        $isFormViewValid = static function (FormView $formView): bool {
58
            return $formView->getVars()['valid'];
59
        };
60
61
        $dataCount = \count($formData);
62
        if (!$dataCount) {
63
            return $this->getResponse($formResource, $_format, true);
64
        }
65
66
        if (1 === $dataCount) {
67
            $formItem = $this->getChildFormByKey($form, $formData);
68
            $formResource->formView = $formView = new FormView($formItem);
69
70
            return $this->getResponse($formResource, $_format, $isFormViewValid($formView));
71
        }
72
73
        $formResources = [];
74
        $valid = true;
75
        foreach ($formData as $key => $value) {
76
            $dataItem = clone $formResource;
77
            $data = is_string($formData[$key]) ? [$key => $formData[$key]] : $formData[$key];
78
            $formItem = $this->getChildFormByKey($form, $data);
79
            $dataItem->formView = $formView = new FormView($formItem);
80
            $formResources[] = $dataItem;
81
            if ($valid && !$isFormViewValid($formView)) {
82
                $valid = false;
83
            }
84
        }
85
86
        return $this->getResponse($formResources, $_format, $valid);
87
    }
88
89
    private function handlePost(Form $formResource, FormInterface $form, string $_format): Response
90
    {
91
        $valid = $form->isValid();
92
        $formResource->formView = new FormView($form);
93
        $context = [];
94
        $response = $formResource;
95
        if ($valid) {
96
            $event = new FormSuccessEvent($formResource, $form, $response);
97
            $this->eventDispatcher->dispatch($event);
98
            $response = $event->response;
99
            $context = $event->serializerContext;
100
        }
101
102
        return $this->getResponse($response, $_format, $valid, $context);
103
    }
104
105
    private function validateDecodedContent(FormInterface $form, $content): array
106
    {
107
        if (!isset($content[$form->getName()])) {
108
            throw new BadRequestHttpException(sprintf('Form object key could not be found. Expected: <b>%s</b>: { "input_name": "input_value" }', $form->getName()));
109
        }
110
111
        return $content[$form->getName()];
112
    }
113
114
    private function getChildFormByKey(FormInterface $form, array $formData): FormInterface
115
    {
116
        $child = $form->get($key = key($formData));
117
        while ($this->isSequentialStringsArray($formData = $formData[$key]) && $count = \count($formData)) {
118
            if (1 === $count) {
119
                $child = $child->get($key = key($formData));
120
                continue;
121
            }
122
            // front-end should submit empty objects for each item in a collection up to the one we are trying to validate
123
            // so let us just get the last item to validate
124
            // key should be numeric, if not it is probably first and second for repeated field. These should both be checked...
125
            $key = ($count - 1);
126
            if (!$child->has($key)) {
127
                break;
128
            }
129
            $child = $child->get($key);
130
        }
131
132
        return $child;
133
    }
134
135
    private function isSequentialStringsArray($data): bool
136
    {
137
        return \is_array($data) && !$this->isAssocArray($data) && $this->arrayIsStrings($data);
138
    }
139
140
    private function isAssocArray(array $arr): bool
141
    {
142
        if ([] === $arr) {
143
            return false;
144
        }
145
146
        return array_keys($arr) !== range(0, \count($arr) - 1);
147
    }
148
149
    private function arrayIsStrings(array $arr): bool
150
    {
151
        foreach ($arr as $item) {
152
            if (!\is_string($item)) {
153
                return false;
154
            }
155
        }
156
157
        return true;
158
    }
159
160
    private function getResponse(
161
        $data,
162
        string $_format,
163
        bool $valid,
164
        array $context = []
165
    ): Response {
166
        $response = new Response();
167
        $response->setStatusCode($valid ? Response::HTTP_OK : Response::HTTP_BAD_REQUEST);
168
        $response->setContent($this->serializer->serialize($data, $_format, $context));
169
170
        return $response;
171
    }
172
}
173