1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
/* |
3
|
|
|
* This file is part of coisa/http. |
4
|
|
|
* |
5
|
|
|
* (c) Felipe Sayão Lobato Abreu <[email protected]> |
6
|
|
|
* |
7
|
|
|
* This source file is subject to the license that is bundled |
8
|
|
|
* with this source code in the file LICENSE. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace CoiSA\Http\Middleware; |
12
|
|
|
|
13
|
|
|
use Fig\Http\Message\RequestMethodInterface; |
14
|
|
|
use Psr\Http\Message\ResponseInterface; |
15
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
16
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
17
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Class RequestMethodMiddleware |
21
|
|
|
* |
22
|
|
|
* @package CoiSA\Http\Middleware |
23
|
|
|
*/ |
24
|
|
|
final class RequestMethodMiddleware implements MiddlewareInterface |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* @var string |
28
|
|
|
*/ |
29
|
|
|
private $method; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var RequestHandlerInterface |
33
|
|
|
*/ |
34
|
|
|
private $handler; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* RequestMethodMiddleware constructor. |
38
|
|
|
* |
39
|
|
|
* @param string $method |
40
|
|
|
* @param RequestHandlerInterface $handler |
41
|
|
|
*/ |
42
|
|
|
public function __construct(string $method, RequestHandlerInterface $handler) |
43
|
|
|
{ |
44
|
|
|
$this->method = \strtoupper($method); |
45
|
|
|
$this->handler = $handler; |
46
|
|
|
|
47
|
|
|
$constant = RequestMethodInterface::class . '::METHOD_' . $this->method; |
48
|
|
|
|
49
|
|
|
if (null === \constant($constant)) { |
50
|
|
|
throw new \UnexpectedValueException('Invalid HTTP method'); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param ServerRequestInterface $request |
56
|
|
|
* @param RequestHandlerInterface $handler |
57
|
|
|
* |
58
|
|
|
* @return ResponseInterface |
59
|
|
|
*/ |
60
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
61
|
|
|
{ |
62
|
|
|
if ($this->method !== $request->getMethod()) { |
63
|
|
|
return $handler->handle($request); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $this->handler->handle($request); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|