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
|
20 |
|
public function __construct(string $queryParamName, array $methodsToOverride) |
30
|
|
|
{ |
31
|
20 |
|
$this->queryParamName = $queryParamName; |
32
|
|
|
|
33
|
20 |
|
\assert( |
34
|
20 |
|
empty(AssertUtils::getNonStrings($methodsToOverride)), |
35
|
20 |
|
'contains non string elements' |
36
|
|
|
); |
37
|
|
|
|
38
|
20 |
|
$this->methodsToOverride = $methodsToOverride; |
39
|
20 |
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param GetResponseEvent $getResponseEvent |
43
|
|
|
*/ |
44
|
19 |
|
public function onKernelRequest(GetResponseEvent $getResponseEvent): void |
45
|
|
|
{ |
46
|
19 |
|
if (!$getResponseEvent->isMasterRequest()) { |
47
|
1 |
|
return; |
48
|
|
|
} |
49
|
|
|
|
50
|
18 |
|
$request = $getResponseEvent->getRequest(); |
51
|
|
|
|
52
|
18 |
|
if (!$request->isMethod(Request::METHOD_GET)) { |
53
|
2 |
|
return; |
54
|
|
|
} |
55
|
|
|
|
56
|
16 |
|
$this->overrideRequestMethod($request); |
57
|
16 |
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param Request $request |
61
|
|
|
*/ |
62
|
16 |
|
protected function overrideRequestMethod(Request $request): void |
63
|
|
|
{ |
64
|
16 |
|
if (!$request->query->has($this->queryParamName)) { |
65
|
14 |
|
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
|
|
|
|