|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Router\Middleware; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\Http\Message\ResponseFactoryInterface; |
|
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
11
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
12
|
|
|
use Yiisoft\Http\Method; |
|
13
|
|
|
use Yiisoft\Http\Status; |
|
14
|
|
|
use Yiisoft\Router\MiddlewareDispatcher; |
|
15
|
|
|
use Yiisoft\Router\UrlMatcherInterface; |
|
16
|
|
|
|
|
17
|
|
|
final class Router implements MiddlewareInterface |
|
18
|
|
|
{ |
|
19
|
|
|
private UrlMatcherInterface $matcher; |
|
20
|
|
|
private ResponseFactoryInterface $responseFactory; |
|
21
|
|
|
private MiddlewareDispatcher $dispatcher; |
|
22
|
3 |
|
private bool $optionsAutoReponse = false; |
|
23
|
|
|
|
|
24
|
3 |
|
public function __construct(UrlMatcherInterface $matcher, ResponseFactoryInterface $responseFactory, MiddlewareDispatcher $dispatcher) |
|
25
|
3 |
|
{ |
|
26
|
3 |
|
$this->matcher = $matcher; |
|
27
|
3 |
|
$this->responseFactory = $responseFactory; |
|
28
|
|
|
$this->dispatcher = $dispatcher; |
|
29
|
3 |
|
} |
|
30
|
|
|
|
|
31
|
3 |
|
public function withOptionsAutoResponse(): self |
|
32
|
|
|
{ |
|
33
|
3 |
|
$new = clone $this; |
|
34
|
1 |
|
$new->optionsAutoReponse = true; |
|
35
|
1 |
|
|
|
36
|
|
|
return $new; |
|
37
|
|
|
} |
|
38
|
2 |
|
|
|
39
|
1 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
40
|
|
|
{ |
|
41
|
|
|
$result = $this->matcher->match($request); |
|
42
|
1 |
|
|
|
43
|
1 |
|
if ($result->isMethodFailure()) { |
|
44
|
|
|
if ($this->optionsAutoReponse && $request->getMethod() === Method::OPTIONS) { |
|
45
|
|
|
return $this->responseFactory->createResponse(Status::NO_CONTENT) |
|
46
|
1 |
|
->withHeader('Allow', implode(', ', $result->methods())); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
return $this->responseFactory->createResponse(Status::METHOD_NOT_ALLOWED) |
|
50
|
|
|
->withHeader('Allow', implode(', ', $result->methods())); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
if (!$result->isSuccess()) { |
|
54
|
|
|
return $handler->handle($request); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
foreach ($result->parameters() as $parameter => $value) { |
|
58
|
|
|
$request = $request->withAttribute($parameter, $value); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
return $result->withDispatcher($this->dispatcher)->process($request, $handler); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|