1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | /* |
||
6 | * (c) Christian Gripp <[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 | namespace Core23\Form\Handler; |
||
13 | |||
14 | use Core23\Form\Handler\Exception\InvalidCallbackException; |
||
15 | use Symfony\Component\Form\FormInterface; |
||
16 | use Symfony\Component\HttpFoundation\Request; |
||
17 | use Symfony\Component\HttpFoundation\Response; |
||
18 | |||
19 | abstract class AbstractFormHandler implements FormHandlerInterface |
||
20 | { |
||
21 | final public function handle(FormInterface $form, Request $request, callable $callback): ?Response |
||
22 | { |
||
23 | if (null !== $response = $this->preProcess($form, $request)) { |
||
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
24 | return $response; |
||
25 | } |
||
26 | |||
27 | $form->handleRequest($request); |
||
28 | |||
29 | if (!$form->isSubmitted() || !$form->isValid()) { |
||
30 | return null; |
||
31 | } |
||
32 | |||
33 | if (null !== $response = $this->validate($form, $request)) { |
||
0 ignored issues
–
show
|
|||
34 | return $response; |
||
35 | } |
||
36 | |||
37 | if (!$this->process($form, $request)) { |
||
38 | return null; |
||
39 | } |
||
40 | |||
41 | $response = $callback(); |
||
42 | |||
43 | if (!$response instanceof Response) { |
||
44 | throw new InvalidCallbackException('Invalid callback response.'); |
||
45 | } |
||
46 | |||
47 | if (null !== $response = $this->postProcess($form, $request, $response)) { |
||
48 | return $response; |
||
49 | } |
||
50 | |||
51 | return null; |
||
52 | } |
||
53 | |||
54 | /** |
||
55 | * Executes before form validating and processing is started. |
||
56 | */ |
||
57 | protected function preProcess(FormInterface $form, Request $request): ?Response |
||
58 | { |
||
59 | return null; |
||
60 | } |
||
61 | |||
62 | /** |
||
63 | * Executes after preprocessing and before form processing is started. |
||
64 | */ |
||
65 | protected function validate(FormInterface $form, Request $request): ?Response |
||
66 | { |
||
67 | return null; |
||
68 | } |
||
69 | |||
70 | /** |
||
71 | * Executes the form processing. |
||
72 | */ |
||
73 | abstract protected function process(FormInterface $form, Request $request): bool; |
||
74 | |||
75 | /** |
||
76 | * Executes after form processing is finished and filters response. |
||
77 | */ |
||
78 | protected function postProcess(FormInterface $form, Request $request, Response $response): ?Response |
||
79 | { |
||
80 | return $response; |
||
81 | } |
||
82 | } |
||
83 |