Passed
Push — master ( b5c2ba...178914 )
by Orkhan
02:45
created

Middleware::ipList()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 21
rs 9.8333
cc 4
nc 4
nop 1
1
<?php
2
3
namespace Orkhanahmadov\LaravelIpMiddleware;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Contracts\Config\Repository;
7
use Illuminate\Contracts\Foundation\Application;
8
use Illuminate\Support\Arr;
9
10
abstract class Middleware
11
{
12
    /**
13
     * @var Application
14
     */
15
    protected $application;
16
    /**
17
     * @var Repository
18
     */
19
    protected $config;
20
21
    /**
22
     * Middleware constructor.
23
     *
24
     * @param Application $application
25
     * @param Repository $config
26
     */
27
    public function __construct(Application $application, Repository $config)
28
    {
29
        $this->application = $application;
30
        $this->config = $config;
31
    }
32
33
    /**
34
     * Returns client IP address.
35
     *
36
     * @param Request $request
37
     * @return string
38
     */
39
    protected function clientIp($request): string
40
    {
41
        return $request->server->get($this->config->get('ip-middleware.custom_server_parameter')) ?? $request->ip();
42
    }
43
44
    /**
45
     * Return result if middleware should IP check.
46
     *
47
     * @return bool
48
     */
49
    protected function shouldCheck(): bool
50
    {
51
        return ! $this->application->environment($this->config->get('ip-middleware.ignore_environments'));
52
    }
53
54
    /**
55
     * Returns IP address list parsed from original middleware parameter.
56
     *
57
     * @param array $list
58
     *
59
     * @return array
60
     */
61
    protected function ipList(array $list): array
62
    {
63
        $originalList = Arr::flatten($list);
64
        $preconfiguredLists = $this->config->get('ip-middleware.lists');
65
66
        $finalList = [];
67
68
        foreach ($originalList as $item) {
69
            if (! isset($preconfiguredLists[$item])) {
70
                $finalList[] = $item;
71
            } else {
72
                if (is_array($preconfiguredLists[$item])) {
73
                    $ipAddresses = $preconfiguredLists[$item];
74
                } else {
75
                    $ipAddresses = explode(',', $preconfiguredLists[$item]);
76
                }
77
                $finalList[] = $ipAddresses;
78
            }
79
        }
80
81
        return Arr::flatten($finalList);
82
    }
83
84
    /**
85
     * Aborts application with configured error code.
86
     */
87
    protected function abort()
88
    {
89
        return $this->application->abort(
90
            $this->config->get('ip-middleware.error_code')
91
        );
92
    }
93
}
94