GetMethodOverrideListener   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 21
c 1
b 0
f 1
dl 0
loc 63
ccs 22
cts 22
cp 1
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A overrideRequestMethod() 0 12 3
A onKernelRequest() 0 13 3
A __construct() 0 10 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiechu\SymfonyCommonsBundle\EventListener;
6
7
use Spiechu\SymfonyCommonsBundle\Utils\AssertUtils;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
10
11
class GetMethodOverrideListener
12
{
13
    public const ATTRIBUTE_REQUEST_GET_METHOD_OVERRIDE = 'spiechu_symfony_commons.event_listener.get_method_override';
14
15
    /**
16
     * @var string
17
     */
18
    protected $queryParamName;
19
20
    /**
21
     * @var string[]
22
     */
23
    protected $methodsToOverride;
24
25
    /**
26
     * @param string   $queryParamName
27
     * @param string[] $methodsToOverride
28
     */
29 24
    public function __construct(string $queryParamName, array $methodsToOverride)
30
    {
31 24
        $this->queryParamName = $queryParamName;
32
33 24
        \assert(
34 24
            !AssertUtils::hasNonStrings($methodsToOverride),
35 24
            '$methodsToOverride contain non string elements'
36
        );
37
38 24
        $this->methodsToOverride = $methodsToOverride;
39 24
    }
40
41
    /**
42
     * @param GetResponseEvent $getResponseEvent
43
     */
44 23
    public function onKernelRequest(GetResponseEvent $getResponseEvent): void
45
    {
46 23
        if (!$getResponseEvent->isMasterRequest()) {
47 1
            return;
48
        }
49
50 22
        $request = $getResponseEvent->getRequest();
51
52 22
        if (!$request->isMethod(Request::METHOD_GET)) {
53 2
            return;
54
        }
55
56 20
        $this->overrideRequestMethod($request);
57 20
    }
58
59
    /**
60
     * @param Request $request
61
     */
62 20
    protected function overrideRequestMethod(Request $request): void
63
    {
64 20
        if (!$request->query->has($this->queryParamName)) {
65 18
            return;
66
        }
67
68 3
        $normalizedQueryParam = strtoupper($request->query->get($this->queryParamName));
69
70 3
        if (\in_array($normalizedQueryParam, $this->methodsToOverride, true)) {
71 2
            $request->setMethod($normalizedQueryParam);
72
73 2
            $request->attributes->set(static::ATTRIBUTE_REQUEST_GET_METHOD_OVERRIDE, $normalizedQueryParam);
74
        }
75 3
    }
76
}
77