1 | <?php |
||
12 | class ClientIp |
||
13 | { |
||
14 | const KEY = 'CLIENT_IPS'; |
||
15 | |||
16 | /** |
||
17 | * @var bool |
||
18 | */ |
||
19 | private $remote = false; |
||
20 | |||
21 | /** |
||
22 | * @var array The trusted headers |
||
23 | */ |
||
24 | private $headers = [ |
||
25 | 'Forwarded', |
||
26 | 'Forwarded-For', |
||
27 | 'Client-Ip', |
||
28 | 'X-Forwarded', |
||
29 | 'X-Forwarded-For', |
||
30 | 'X-Cluster-Client-Ip', |
||
31 | ]; |
||
32 | |||
33 | /** |
||
34 | * Returns all ips found. |
||
35 | * |
||
36 | * @param ServerRequestInterface $request |
||
37 | * |
||
38 | * @return array|null |
||
39 | */ |
||
40 | public static function getIps(ServerRequestInterface $request) |
||
44 | |||
45 | /** |
||
46 | * Return the client ip. |
||
47 | * |
||
48 | * @param ServerRequestInterface $request |
||
49 | * |
||
50 | * @return string|null |
||
51 | */ |
||
52 | public static function getIp(ServerRequestInterface $request) |
||
58 | |||
59 | /** |
||
60 | * Constructor. Defines de trusted headers. |
||
61 | * |
||
62 | * @param null|array $headers |
||
63 | */ |
||
64 | public function __construct(array $headers = null) |
||
70 | |||
71 | /** |
||
72 | * Configure the trusted headers. |
||
73 | * |
||
74 | * @param array $headers |
||
75 | * |
||
76 | * @return self |
||
77 | */ |
||
78 | public function headers(array $headers) |
||
84 | |||
85 | /** |
||
86 | * To get the ip from a remote service. |
||
87 | * Useful for testing purposes on localhost. |
||
88 | * |
||
89 | * @param bool $remote |
||
90 | * |
||
91 | * @return self |
||
92 | */ |
||
93 | public function remote($remote = true) |
||
99 | |||
100 | /** |
||
101 | * Execute the middleware. |
||
102 | * |
||
103 | * @param ServerRequestInterface $request |
||
104 | * @param ResponseInterface $response |
||
105 | * @param callable $next |
||
106 | * |
||
107 | * @return ResponseInterface |
||
108 | */ |
||
109 | public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
||
115 | |||
116 | /** |
||
117 | * Detect and return all ips found. |
||
118 | * |
||
119 | * @param ServerRequestInterface $request |
||
120 | * |
||
121 | * @return array |
||
122 | */ |
||
123 | private function scanIps(ServerRequestInterface $request) |
||
150 | } |
||
151 |