Passed
Push — master ( 3d5791...3d4063 )
by Orkhan
02:52 queued 10s
created

WhitelistMiddleware::handle()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 2
nop 3
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Orkhanahmadov\LaravelIpMiddleware;
4
5
use Closure;
6
use Illuminate\Support\Arr;
7
use Illuminate\Http\Request;
8
use Illuminate\Http\Response;
9
use Illuminate\Contracts\Config\Repository;
10
use Illuminate\Contracts\Foundation\Application;
11
12
class WhitelistMiddleware
13
{
14
    /**
15
     * @var Application
16
     */
17
    private $application;
18
    /**
19
     * @var Repository
20
     */
21
    private $config;
22
23
    /**
24
     * IpMiddleware constructor.
25
     *
26
     * @param Application $application
27
     * @param Repository $config
28
     */
29
    public function __construct(Application $application, Repository $config)
30
    {
31
        $this->application = $application;
32
        $this->config = $config;
33
    }
34
35
    /**
36
     * Handle an incoming request.
37
     *
38
     * @param Request $request
39
     * @param Closure $next
40
     * @param array $allowedIp
41
     *
42
     * @return mixed
43
     */
44
    public function handle($request, Closure $next, ...$allowedIp)
45
    {
46
        $clientIp = $request->server('HTTP_CF_CONNECTING_IP') ?? $request->ip();
47
48
        if (!$this->application->environment($this->config->get('ip-middleware.ignore_environments')) &&
49
            !in_array($clientIp, Arr::flatten($allowedIp))
50
        ) {
51
            abort($this->config->get('ip-middleware.error_code'));
52
        }
53
54
        return $next($request);
55
    }
56
}
57