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