Passed
Push — master ( 37bd73...0020d0 )
by Orkhan
02:25
created

Middleware::parsePredefinedListItem()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Orkhanahmadov\LaravelIpMiddleware;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Http\Request;
7
use Illuminate\Contracts\Config\Repository;
8
use Illuminate\Contracts\Foundation\Application;
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<string> $list
58
     *
59
     * @return array<string>
60
     */
61
    protected function ipList(array $list): array
62
    {
63
        $predefinedLists = $this->config->get('ip-middleware.predefined_lists');
64
65
        $finalList = [];
66
        foreach (Arr::flatten($list) as $item) {
67
            if (isset($predefinedLists[$item])) {
68
                $finalList[] = $this->parsePredefinedListItem($predefinedLists[$item]);
69
            } else {
70
                $finalList[] = $item;
71
            }
72
        }
73
74
        return Arr::flatten($finalList);
75
    }
76
77
    /**
78
     * @param array<string>|string $item
79
     *
80
     * @return array<string>
81
     */
82
    private function parsePredefinedListItem($item): array
83
    {
84
        if (is_array($item)) {
85
            return $item;
86
        }
87
88
        return explode(',', $item);
89
    }
90
91
    /**
92
     * Aborts application with configured error code.
93
     */
94
    protected function abort()
95
    {
96
        return $this->application->abort(
97
            $this->config->get('ip-middleware.error_code')
98
        );
99
    }
100
}
101