Completed
Push — master ( 12bc5d...f69768 )
by Oscar
58:41
created

Https::__invoke()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.2
cc 4
eloc 7
nc 3
nop 3
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);
0 ignored issues
show
Security Bug introduced by
It seems like $this->redirectStatus can also be of type false; however, Psr7Middlewares\Utils\Re...::getRedirectResponse() does only seem to accept integer, did you maybe forget to handle an error condition?
Loading history...
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