BlacklistMiddleware   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 4
dl 0
loc 41
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A process() 0 9 2
A isForbidden() 0 9 3
A getIp() 0 11 2
1
<?php
2
3
namespace hiapi\Core\Http\Psr15\Middleware;
4
5
use hiapi\exceptions\NotAuthenticatedException;
6
use hiapi\Core\Utils\CIDR;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
12
class BlacklistMiddleware implements MiddlewareInterface
13
{
14
    private $restriction;
15
16
    public function __construct($restriction)
17
    {
18
        $this->restriction = $restriction;
19
    }
20
21
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
22
    {
23
        $ip = $this->getIp($request);
24
        if ($this->isForbidden($ip)) {
25
            throw new NotAuthenticatedException('Forbidden IP: ' . $ip);
26
        }
27
28
        return $handler->handle($request);
29
    }
30
31
    private function isForbidden(string $ip): bool
32
    {
33
        if (is_array($this->restriction)) {
34
            return CIDR::matchBulk($ip, $this->restriction);
35
        } elseif ($this->restriction instanceof \Closure) {
36
            return call_user_func($this->restriction, $ip);
37
        }
38
        return false;
39
    }
40
41
    private function getIp(ServerRequestInterface $request): string
42
    {
43
        $ip = $request->getAttribute(UserRealIpMiddleware::ATTRIBUTE_NAME);
44
        if (!empty($ip)) {
45
            return $ip;
46
        }
47
48
        $params = $request->getServerParams();
49
50
        return $params['REMOTE_ADDR'] ?? '';
51
    }
52
}
53