BlacklistMiddleware::getIp()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 1
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