1 | <?php |
||
19 | class ClientIp |
||
20 | { |
||
21 | use Utils\AttributeTrait; |
||
22 | |||
23 | const KEY = 'CLIENT_IPS'; |
||
24 | |||
25 | /** |
||
26 | * @var bool |
||
27 | */ |
||
28 | private $remote = false; |
||
29 | |||
30 | /** |
||
31 | * @var array The trusted headers |
||
32 | */ |
||
33 | private $headers = [ |
||
34 | 'Forwarded', |
||
35 | 'Forwarded-For', |
||
36 | 'Client-Ip', |
||
37 | 'X-Forwarded', |
||
38 | 'X-Forwarded-For', |
||
39 | 'X-Cluster-Client-Ip', |
||
40 | ]; |
||
41 | |||
42 | /** |
||
43 | * @var array Server options to be checked for IP location, checked in a given order. |
||
44 | */ |
||
45 | private $serverOptions = [ |
||
46 | 'REMOTE_ADDR', |
||
47 | 'HTTP_X_FORWARDED_FOR' |
||
48 | ]; |
||
49 | |||
50 | /** |
||
51 | * Returns all ips found. |
||
52 | * |
||
53 | * @param ServerRequestInterface $request |
||
54 | * |
||
55 | * @return array|null |
||
56 | */ |
||
57 | public static function getIps(ServerRequestInterface $request) |
||
61 | |||
62 | /** |
||
63 | * Return the client ip. |
||
64 | * |
||
65 | * @param ServerRequestInterface $request |
||
66 | * |
||
67 | * @return string|null |
||
68 | */ |
||
69 | public static function getIp(ServerRequestInterface $request) |
||
75 | |||
76 | /** |
||
77 | * Constructor. Defines de trusted headers. |
||
78 | * |
||
79 | * @param null|array $headers |
||
80 | */ |
||
81 | public function __construct(array $headers = null) |
||
87 | |||
88 | /** |
||
89 | * Configure the trusted headers. |
||
90 | * |
||
91 | * @param array $headers |
||
92 | * |
||
93 | * @return self |
||
94 | */ |
||
95 | public function headers(array $headers) |
||
101 | |||
102 | /** |
||
103 | * Configure the serverOptions to be checked for id address. |
||
104 | * |
||
105 | * @param array $serverOptions |
||
106 | * |
||
107 | * @return self |
||
108 | */ |
||
109 | public function serverOptions(array $serverOptions) |
||
115 | |||
116 | /** |
||
117 | * To get the ip from a remote service. |
||
118 | * Useful for testing purposes on localhost. |
||
119 | * |
||
120 | * @param bool $remote |
||
121 | * |
||
122 | * @return self |
||
123 | */ |
||
124 | public function remote($remote = true) |
||
130 | |||
131 | /** |
||
132 | * Execute the middleware. |
||
133 | * |
||
134 | * @param ServerRequestInterface $request |
||
135 | * @param ResponseInterface $response |
||
136 | * @param callable $next |
||
137 | * |
||
138 | * @return ResponseInterface |
||
139 | */ |
||
140 | public function __invoke( |
||
149 | |||
150 | /** |
||
151 | * Detect and return all ips found. |
||
152 | * |
||
153 | * @param ServerRequestInterface $request |
||
154 | * |
||
155 | * @return array |
||
156 | */ |
||
157 | private function scanIps(ServerRequestInterface $request) |
||
190 | } |
||
191 |