Completed
Pull Request — master (#311)
by Łukasz
03:20
created

AbstractFormSubmitHandler::handleRequest()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 12
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * (c) FSi sp. z o.o. <[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 FSi\Bundle\AdminBundle\Admin\Context\Request;
13
14
use FSi\Bundle\AdminBundle\Event\AdminEvent;
15
use FSi\Bundle\AdminBundle\Event\FormEvent;
16
use FSi\Bundle\AdminBundle\Exception\RequestHandlerException;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
20
abstract class AbstractFormSubmitHandler extends AbstractHandler
21
{
22
    public function handleRequest(AdminEvent $event, Request $request): ?Response
23
    {
24
        $event = $this->validateEvent($event);
25
26
        if (!$request->isMethod('POST')) {
27
            return null;
28
        }
29
30
        $this->eventDispatcher->dispatch($this->getPreSubmitEventName(), $event);
31
        if ($event->hasResponse()) {
32
            return $event->getResponse();
33
        }
34
35
        $event->getForm()->handleRequest($request);
36
37
        $this->eventDispatcher->dispatch($this->getPostSubmitEventName(), $event);
38
        if ($event->hasResponse()) {
39
            return $event->getResponse();
40
        }
41
42
        return null;
43
    }
44
45
    private function validateEvent(AdminEvent $event): FormEvent
46
    {
47
        if (!$event instanceof FormEvent) {
48
            throw new RequestHandlerException(sprintf('%s requires FormEvent', get_class($this)));
49
        }
50
51
        return $event;
52
    }
53
54
    abstract protected function getPreSubmitEventName(): string;
55
56
    abstract protected function getPostSubmitEventName(): string;
57
}
58