Passed
Push — v2 ( 9b853e...868892 )
by Daniel
04:58
created

FormSubmitHandler::arrayIsStrings()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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