1 | <?php |
||
12 | class ClientIp |
||
13 | { |
||
14 | use Utils\AttributeTrait; |
||
15 | |||
16 | const KEY = 'CLIENT_IPS'; |
||
17 | |||
18 | /** |
||
19 | * @var bool |
||
20 | */ |
||
21 | private $remote = false; |
||
22 | |||
23 | /** |
||
24 | * @var array The trusted headers |
||
25 | */ |
||
26 | private $headers = []; |
||
27 | |||
28 | /** |
||
29 | * Returns all ips found. |
||
30 | * |
||
31 | * @param ServerRequestInterface $request |
||
32 | * |
||
33 | * @return array|null |
||
34 | */ |
||
35 | public static function getIps(ServerRequestInterface $request) |
||
39 | |||
40 | /** |
||
41 | * Return the client ip. |
||
42 | * |
||
43 | * @param ServerRequestInterface $request |
||
44 | * |
||
45 | * @return string|null |
||
46 | */ |
||
47 | public static function getIp(ServerRequestInterface $request) |
||
53 | |||
54 | /** |
||
55 | * Constructor. Defines de trusted headers. |
||
56 | * |
||
57 | * @param null|array $headers |
||
58 | */ |
||
59 | public function __construct(array $headers = null) |
||
67 | |||
68 | /** |
||
69 | * Configure the trusted headers. |
||
70 | * |
||
71 | * @param array $headers |
||
72 | * |
||
73 | * @return self |
||
74 | */ |
||
75 | public function headers(array $headers = ['Forwarded', 'Forwarded-For', 'Client-Ip', 'X-Forwarded', 'X-Forwarded-For', 'X-Cluster-Client-Ip']) |
||
81 | |||
82 | /** |
||
83 | * To get the ip from a remote service. |
||
84 | * Useful for testing purposes on localhost. |
||
85 | * |
||
86 | * @param bool $remote |
||
87 | * |
||
88 | * @return self |
||
89 | */ |
||
90 | public function remote($remote = true) |
||
96 | |||
97 | /** |
||
98 | * Execute the middleware. |
||
99 | * |
||
100 | * @param ServerRequestInterface $request |
||
101 | * @param ResponseInterface $response |
||
102 | * @param callable $next |
||
103 | * |
||
104 | * @return ResponseInterface |
||
105 | */ |
||
106 | public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
||
112 | |||
113 | /** |
||
114 | * Detect and return all ips found. |
||
115 | * |
||
116 | * @param ServerRequestInterface $request |
||
117 | * |
||
118 | * @return array |
||
119 | */ |
||
120 | private function scanIps(ServerRequestInterface $request) |
||
147 | } |
||
148 |