Passed
Pull Request — master (#317)
by Łukasz
16:24
created

AbstractFormSubmitHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
dl 0
loc 37
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validateEvent() 0 7 2
A handleRequest() 0 21 4
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