Passed
Pull Request — master (#317)
by Łukasz
02:39
created

AbstractFormSubmitHandler::handleRequest()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.0534
c 0
b 0
f 0
cc 4
eloc 11
nc 4
nop 2
1
<?php
2
3
/**
4
 * (c) FSi sp. z o.o. <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
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(Request::METHOD_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