1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Psr7Middlewares\Middleware; |
4
|
|
|
|
5
|
|
|
use Psr7Middlewares\Utils; |
6
|
|
|
use Psr\Http\Message\RequestInterface; |
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Middleware to redirect to https protocol. |
11
|
|
|
*/ |
12
|
|
|
class Https |
13
|
|
|
{ |
14
|
|
|
use Utils\RedirectTrait; |
15
|
|
|
|
16
|
|
|
const HEADER = 'Strict-Transport-Security'; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param int One year by default |
20
|
|
|
*/ |
21
|
|
|
private $maxAge = 31536000; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param bool Whether include subdomains |
25
|
|
|
*/ |
26
|
|
|
private $includeSubdomains = false; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Set basic config. |
30
|
|
|
*/ |
31
|
|
|
public function __construct() |
32
|
|
|
{ |
33
|
|
|
$this->redirect(301); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Configure the max-age HSTS in seconds. |
38
|
|
|
* |
39
|
|
|
* @param int $maxAge |
40
|
|
|
* |
41
|
|
|
* @return self |
42
|
|
|
*/ |
43
|
|
|
public function maxAge($maxAge) |
44
|
|
|
{ |
45
|
|
|
$this->maxAge = $maxAge; |
46
|
|
|
|
47
|
|
|
return $this; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Configure the includeSubDomains HSTS directive. |
52
|
|
|
* |
53
|
|
|
* @param bool $includeSubdomains |
54
|
|
|
* |
55
|
|
|
* @return self |
56
|
|
|
*/ |
57
|
|
|
public function includeSubdomains($includeSubdomains = true) |
58
|
|
|
{ |
59
|
|
|
$this->includeSubdomains = $includeSubdomains; |
60
|
|
|
|
61
|
|
|
return $this; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Execute the middleware. |
66
|
|
|
* |
67
|
|
|
* @param RequestInterface $request |
68
|
|
|
* @param ResponseInterface $response |
69
|
|
|
* @param callable $next |
70
|
|
|
* |
71
|
|
|
* @return ResponseInterface |
72
|
|
|
*/ |
73
|
|
|
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) |
74
|
|
|
{ |
75
|
|
|
$uri = $request->getUri(); |
76
|
|
|
|
77
|
|
|
if (strtolower($uri->getScheme()) !== 'https') { |
78
|
|
|
return self::getRedirectResponse($this->redirectStatus, $uri->withScheme('https'), $response); |
|
|
|
|
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
if (!empty($this->maxAge)) { |
82
|
|
|
$response = $response->withHeader(self::HEADER, sprintf('max-age=%d%s', $this->maxAge, $this->includeSubdomains ? ';includeSubDomains' : '')); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
return $next($request, $response); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|