1 | <?php |
||
10 | class RestrictRoute |
||
11 | { |
||
12 | protected $options = [ |
||
13 | 'ip' => null, |
||
14 | ]; |
||
15 | |||
16 | /** |
||
17 | * Create new RestrictRoute service provider. |
||
18 | * |
||
19 | * @param array $options |
||
20 | */ |
||
21 | 6 | public function __construct(array $options = []) |
|
25 | |||
26 | /** |
||
27 | * RestrictRoute middleware invokable class. |
||
28 | * |
||
29 | * @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request |
||
30 | * @param \Psr\Http\Message\ResponseInterface $response PSR7 response |
||
31 | * @param callable $next Next middleware |
||
32 | * |
||
33 | * @return \Psr\Http\Message\ResponseInterface |
||
34 | */ |
||
35 | 6 | public function __invoke($request, $response, $next) |
|
36 | { |
||
37 | 6 | $ipAddress = $request->getAttribute('ip_address'); |
|
38 | 6 | if ($this->options['ip']) { |
|
39 | 6 | if (is_array($this->options['ip'])) { |
|
40 | 2 | $isAllowed = false; |
|
41 | 2 | foreach ($this->options['ip'] as $range) { |
|
42 | 2 | if (v::ip($range)->validate($ipAddress)) { |
|
43 | 2 | $isAllowed = true; |
|
44 | } |
||
45 | } |
||
46 | 2 | if ($isAllowed === false) { |
|
47 | 2 | return $response->withStatus(401); |
|
48 | } |
||
49 | 4 | } elseif (!v::ip($this->options['ip'])->validate($ipAddress)) { |
|
50 | 2 | return $response->withStatus(401); |
|
51 | } |
||
52 | } |
||
53 | |||
54 | 3 | return $next($request, $response); |
|
55 | } |
||
56 | |||
57 | /** |
||
58 | * Get the options array. |
||
59 | * |
||
60 | * @return array |
||
61 | */ |
||
62 | 1 | public function getOptions() |
|
66 | |||
67 | /** |
||
68 | * Set the options array. |
||
69 | * |
||
70 | * @param array $options The options array. |
||
71 | */ |
||
72 | 1 | public function setOptions($options) |
|
76 | } |
||
77 |