|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Psr7Middlewares\Utils; |
|
4
|
|
|
|
|
5
|
|
|
use Psr7Middlewares\Middleware\BasePath; |
|
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
8
|
|
|
use Psr\Http\Message\UriInterface; |
|
9
|
|
|
use InvalidArgumentException; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Trait used by all middlewares with redirect() option. |
|
13
|
|
|
*/ |
|
14
|
|
|
trait RedirectTrait |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @var int|false Redirect HTTP status code |
|
18
|
|
|
*/ |
|
19
|
|
|
private $redirectStatus = false; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Set HTTP redirect status code. |
|
23
|
|
|
* |
|
24
|
|
|
* @param int|false $redirectStatus Redirect HTTP status code |
|
25
|
|
|
* |
|
26
|
|
|
* @return self |
|
27
|
|
|
*/ |
|
28
|
|
|
public function redirect($redirectStatus = 302) |
|
29
|
|
|
{ |
|
30
|
|
|
if (!in_array($redirectStatus, [false, 301, 302], true)) { |
|
31
|
|
|
throw new InvalidArgumentException('The redirect status code must be 301, 302 or false'); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
$this->redirectStatus = $redirectStatus; |
|
35
|
|
|
|
|
36
|
|
|
return $this; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Returns a redirect response. |
|
41
|
|
|
* |
|
42
|
|
|
* @param ServerRequestInterface $request |
|
43
|
|
|
* @param UriInterface $uri |
|
44
|
|
|
* @param ResponseInterface $response |
|
45
|
|
|
* |
|
46
|
|
|
* @return ResponseInterface |
|
47
|
|
|
*/ |
|
48
|
|
|
private function getRedirectResponse(ServerRequestInterface $request, UriInterface $uri, ResponseInterface $response) |
|
49
|
|
|
{ |
|
50
|
|
|
//Fix the basePath |
|
51
|
|
|
$generator = BasePath::getGenerator($request); |
|
52
|
|
|
|
|
53
|
|
|
if ($generator !== null) { |
|
54
|
|
|
$uri = $uri->withPath($generator($uri->getPath())); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
return $response |
|
58
|
|
|
->withStatus($this->redirectStatus) |
|
59
|
|
|
->withHeader('Location', (string) $uri); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|