|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Silverback\ApiComponentBundle\Controller; |
|
4
|
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
|
6
|
|
|
use Silverback\ApiComponentBundle\Entity\Component\Form\Form; |
|
7
|
|
|
use Silverback\ApiComponentBundle\DTO\Form\FormView; |
|
8
|
|
|
use Silverback\ApiComponentBundle\Factory\Form\FormFactory; |
|
9
|
|
|
use Silverback\ApiComponentBundle\Form\Handler\FormHandlerInterface; |
|
10
|
|
|
use Silverback\ApiComponentBundle\Validator\ClassNameValidator; |
|
11
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
12
|
|
|
use Symfony\Component\HttpFoundation\Response; |
|
13
|
|
|
use Symfony\Component\Serializer\SerializerInterface; |
|
14
|
|
|
|
|
15
|
|
|
class FormPostAction extends AbstractFormAction |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var iterable|FormHandlerInterface[] |
|
19
|
|
|
*/ |
|
20
|
|
|
private $handlers; |
|
21
|
|
|
|
|
22
|
|
|
public function __construct( |
|
23
|
|
|
EntityManagerInterface $entityManager, |
|
24
|
|
|
SerializerInterface $serializer, |
|
25
|
|
|
FormFactory $formFactory, |
|
26
|
|
|
iterable $formHandlers |
|
27
|
|
|
) { |
|
28
|
|
|
parent::__construct($entityManager, $serializer, $formFactory); |
|
29
|
|
|
$this->handlers = $formHandlers; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* @param Request $request |
|
34
|
|
|
* @param Form $data |
|
35
|
|
|
* @return Response |
|
36
|
|
|
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException |
|
37
|
|
|
* @throws \Symfony\Component\Form\Exception\AlreadySubmittedException |
|
38
|
|
|
* @throws \UnexpectedValueException |
|
39
|
|
|
* @throws \InvalidArgumentException |
|
40
|
|
|
* @throws \Symfony\Component\Form\Exception\LogicException |
|
41
|
|
|
* @throws \BadMethodCallException |
|
42
|
|
|
* @throws \LogicException |
|
43
|
|
|
*/ |
|
44
|
|
|
public function __invoke(Request $request, Form $data) |
|
45
|
|
|
{ |
|
46
|
|
|
$contentType = $request->headers->get('CONTENT_TYPE'); |
|
47
|
|
|
$_format = $request->attributes->get('_format') ?: $request->getFormat($contentType); |
|
48
|
|
|
|
|
49
|
|
|
$form = $this->formFactory->create($data); |
|
50
|
|
|
$formData = $this->deserializeFormData($form, $request->getContent()); |
|
51
|
|
|
$form->submit($formData); |
|
52
|
|
|
if (!$form->isSubmitted()) { |
|
53
|
|
|
return $this->getResponse($data, $_format, false); |
|
54
|
|
|
} |
|
55
|
|
|
$valid = $form->isValid(); |
|
56
|
|
|
$data->setForm(new FormView($form->createView())); |
|
57
|
|
|
if ($valid && $data->getSuccessHandler()) { |
|
58
|
|
|
foreach ($this->handlers as $handler) { |
|
59
|
|
|
if (ClassNameValidator::isClassSame($data->getSuccessHandler(), $handler)) { |
|
60
|
|
|
$handler->success($data); |
|
61
|
|
|
break; |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
return $this->getResponse($data, $_format, $valid); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|