Completed
Push — v2 ( ffeacf...36b0ac )
by Daniel
04:25
created

FormSubmitHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 2
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 InvalidArgumentException;
17
use JsonException;
18
use Silverback\ApiComponentBundle\ApiComponentBundleEvents;
19
use Silverback\ApiComponentBundle\Dto\Form\FormView;
20
use Silverback\ApiComponentBundle\Entity\Component\Form;
21
use Silverback\ApiComponentBundle\Event\FormSuccessEvent;
22
use Silverback\ApiComponentBundle\Form\Factory\FormFactory;
23
use Symfony\Component\EventDispatcher\EventDispatcher;
24
use Symfony\Component\Form\FormInterface;
25
use Symfony\Component\HttpFoundation\Request;
26
use Symfony\Component\HttpFoundation\Response;
27
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
28
use Symfony\Component\Serializer\SerializerInterface;
29
use function json_decode;
30
31
/**
32
 * @author Daniel West <[email protected]>
33
 */
34
class FormSubmitHandler
35
{
36
    private FormFactory $formFactory;
37
    private EventDispatcher $eventDispatcher;
38
    private SerializerInterface $serializer;
39
40
    public function __construct(FormFactory $formFactory, EventDispatcher $eventDispatcher, SerializerInterface $serializer)
41
    {
42
        $this->formFactory = $formFactory;
43
        $this->eventDispatcher = $eventDispatcher;
44
        $this->serializer = $serializer;
45
    }
46
47
    public function handle(Request $request, Form $formResource, string $_format): Response
48
    {
49
        $builder = $this->formFactory->create($formResource);
50
        $form = $builder->getForm();
51
        $formData = $this->deserializeFormData($form, $request->getContent());
52
        $isPatchRequest = Request::METHOD_PATCH === $request->getMethod();
53
        $form->submit($formData, !$isPatchRequest);
54
        if ($isPatchRequest) {
55
            return $this->handlePatch($formResource, $form, $_format, $formData);
56
        }
57
58
        return $this->handlePost($formResource, $form, $_format);
59
    }
60
61
    private function handlePatch(Form $formResource, FormInterface $form, string $_format, array $formData): Response
62
    {
63
        $isFormViewValid = static function (FormView $formView): bool {
64
            return $formView->getVars()['valid'];
65
        };
66
67
        $dataCount = \count($formData);
68
        if (1 === $dataCount) {
69
            $formItem = $this->getChildFormByKey($form, $formData);
70
            $formResource->form = $formView = new FormView($formItem);
71
72
            return $this->getResponse($formResource, $_format, $isFormViewValid($formView));
73
        }
74
75
        $formResources = [];
76
        $valid = true;
77
        foreach ($formData as $key => $value) {
78
            $dataItem = clone $formResource;
79
            $formItem = $this->getChildFormByKey($form, $formData[$key]);
80
            $dataItem->form = $formView = new FormView($formItem);
81
            $formResources[] = $dataItem;
82
            if ($valid && !$isFormViewValid($formView)) {
83
                $valid = false;
84
            }
85
        }
86
87
        return $this->getResponse($formResources, $_format, $valid);
88
    }
89
90
    private function handlePost(Form $formResource, FormInterface $form, string $_format): Response
91
    {
92
        $valid = $form->isValid();
93
        $formResource->form = new FormView($form);
94
        $context = [];
95
        if ($valid) {
96
            $event = new FormSuccessEvent($formResource, $form);
97
            $this->eventDispatcher->dispatch($event, ApiComponentBundleEvents::FORM_SUCCESS);
98
            $context = $event->serializerContext;
99
        }
100
101
        return $this->getResponse($formResource, $_format, $valid, $context);
102
    }
103
104
    private function deserializeFormData(FormInterface $form, $content): array
105
    {
106
        try {
107
            $decoded = json_decode($content, true, 512, JSON_THROW_ON_ERROR | 0);
108
        } catch (JsonException $exception) {
109
            throw new InvalidArgumentException('json_decode error: ' . $exception->getMessage());
110
        }
111
        if (!isset($decoded[$form->getName()])) {
112
            throw new BadRequestHttpException(sprintf('Form object key could not be found. Expected: <b>%s</b>: { "input_name": "input_value" }', $form->getName()));
113
        }
114
115
        return $decoded[$form->getName()];
116
    }
117
118
    private function getChildFormByKey(FormInterface $form, array $formData): FormInterface
119
    {
120
        $child = $form->get($key = key($formData));
121
        while ($this->isSequentialStringsArray($formData = $formData[$key]) && $count = \count($formData)) {
122
            if (1 === $count) {
123
                $child = $child->get($key = key($formData));
124
                continue;
125
            }
126
            // front-end should submit empty objects for each item in a collection up to the one we are trying to validate
127
            // so let us just get the last item to validate
128
            // key should be numeric, if not it is probably first and second for repeated field. These should both be checked...
129
            $key = ($count - 1);
130
            if (!$child->has($key)) {
131
                break;
132
            }
133
            $child = $child->get($key);
134
        }
135
136
        return $child;
137
    }
138
139
    private function isSequentialStringsArray($data): bool
140
    {
141
        return \is_array($data) && !$this->isAssocArray($data) && $this->arrayIsStrings($data);
142
    }
143
144
    private function isAssocArray(array $arr): bool
145
    {
146
        if ([] === $arr) {
147
            return false;
148
        }
149
150
        return array_keys($arr) !== range(0, \count($arr) - 1);
151
    }
152
153
    private function arrayIsStrings(array $arr): bool
154
    {
155
        foreach ($arr as $item) {
156
            if (!\is_string($item)) {
157
                return false;
158
            }
159
        }
160
161
        return true;
162
    }
163
164
    private function getResponse(
165
        $data,
166
        string $_format,
167
        bool $valid,
168
        array $context = []
169
    ): Response {
170
        $response = new Response();
171
        $response->setStatusCode($valid ? Response::HTTP_OK : Response::HTTP_BAD_REQUEST);
172
        $response->setContent($this->serializer->serialize($data, $_format, $context));
173
174
        return $response;
175
    }
176
}
177