Completed
Push — master ( 779b44...4003b7 )
by Davide
01:25
created

RestrictRoute::__invoke()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 20
cp 0
rs 7.551
c 0
b 0
f 0
cc 7
eloc 13
nc 5
nop 3
crap 56
1
<?php
2
3
namespace DavidePastore\Slim\RestrictRoute;
4
5
use Respect\Validation\Validator as v;
6
7
/**
8
 * RestrictRoute for Slim.
9
 */
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
    public function __construct(array $options = [])
22
    {
23
        $this->options = array_merge($this->options, $options);
24
    }
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
    public function __invoke($request, $response, $next)
36
    {
37
        $ipAddress = $request->getAttribute('ip_address');
38
        if ($this->options['ip']) {
39
            if (is_array($this->options['ip'])) {
40
                $isAllowed = false;
41
                foreach ($this->options['ip'] as $range) {
42
                    if (v::ip($range)->validate($ipAddress)) {
43
                        $isAllowed = true;
44
                    }
45
                }
46
                if ($isAllowed === false) {
47
                    return $response->withStatus(401);
48
                }
49
            } elseif (!v::ip($this->options['ip'])->validate($ipAddress)) {
50
                return $response->withStatus(401);
51
            }
52
        }
53
54
        return $next($request, $response);
55
    }
56
57
    /**
58
     * Get the options array.
59
     *
60
     * @return array
61
     */
62
    public function getOptions()
63
    {
64
        return $this->options;
65
    }
66
67
    /**
68
     * Set the options array.
69
     *
70
     * @param array $options The options array.
71
     */
72
    public function setOptions($options)
73
    {
74
        $this->options = $options;
75
    }
76
}
77