|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Yii\Web\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\Status; |
|
13
|
|
|
use Yiisoft\Router\UrlGeneratorInterface; |
|
14
|
|
|
|
|
15
|
|
|
final class Redirect implements MiddlewareInterface |
|
16
|
|
|
{ |
|
17
|
|
|
private ?string $uri = null; |
|
18
|
|
|
private ?string $route = null; |
|
19
|
|
|
private array $parameters = []; |
|
20
|
|
|
private int $statusCode = Status::MOVED_PERMANENTLY; |
|
21
|
|
|
private ResponseFactoryInterface $responseFactory; |
|
22
|
|
|
private UrlGeneratorInterface $urlGenerator; |
|
23
|
|
|
|
|
24
|
6 |
|
public function __construct(ResponseFactoryInterface $responseFactory, UrlGeneratorInterface $urlGenerator) |
|
25
|
|
|
{ |
|
26
|
6 |
|
$this->responseFactory = $responseFactory; |
|
27
|
6 |
|
$this->urlGenerator = $urlGenerator; |
|
28
|
6 |
|
} |
|
29
|
|
|
|
|
30
|
1 |
|
public function toUrl(string $url): self |
|
31
|
|
|
{ |
|
32
|
1 |
|
$new = clone $this; |
|
33
|
1 |
|
$new->uri = $url; |
|
34
|
1 |
|
return $new; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
4 |
|
public function toRoute(string $name, array $parameters = []): self |
|
38
|
|
|
{ |
|
39
|
4 |
|
$new = clone $this; |
|
40
|
4 |
|
$new->route = $name; |
|
41
|
4 |
|
$new->parameters = $parameters; |
|
42
|
4 |
|
return $new; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
1 |
|
public function withStatus(int $code): self |
|
46
|
|
|
{ |
|
47
|
1 |
|
$new = clone $this; |
|
48
|
1 |
|
$new->statusCode = $code; |
|
49
|
1 |
|
return $new; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
1 |
|
public function permanent(): self |
|
53
|
|
|
{ |
|
54
|
1 |
|
$new = clone $this; |
|
55
|
1 |
|
$new->statusCode = Status::MOVED_PERMANENTLY; |
|
56
|
1 |
|
return $new; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
1 |
|
public function temporary(): self |
|
60
|
|
|
{ |
|
61
|
1 |
|
$new = clone $this; |
|
62
|
1 |
|
$new->statusCode = Status::SEE_OTHER; |
|
63
|
1 |
|
return $new; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
6 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
67
|
|
|
{ |
|
68
|
6 |
|
if ($this->route === null && $this->uri === null) { |
|
69
|
1 |
|
throw new \InvalidArgumentException('Either toUrl() or toRoute() should be used.'); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
5 |
|
$uri = $this->uri ?? $this->urlGenerator->generate($this->route, $this->parameters); |
|
|
|
|
|
|
73
|
|
|
|
|
74
|
5 |
|
return $this->responseFactory |
|
75
|
5 |
|
->createResponse($this->statusCode) |
|
76
|
5 |
|
->withAddedHeader('Location', $uri); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|