Просмотр файла app/Middleware/IpAddressMiddleware.php

Размер файла: 2.04Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Middleware;
  6.  
  7. use Psr\Http\Message\ResponseInterface as Response;
  8. use Psr\Http\Message\ServerRequestInterface as Request;
  9. use Psr\Http\Server\MiddlewareInterface as Middleware;
  10. use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
  11.  
  12. final class IpAddressMiddleware implements Middleware
  13. {
  14. public function process(
  15. Request $request,
  16. RequestHandler $handler,
  17. ): Response {
  18.  
  19. $ipAddress = $this->determineClientIpAddress($request);
  20.  
  21. $request = $request->withAttribute('ip', $ipAddress);
  22.  
  23. return $handler->handle($request);
  24. }
  25.  
  26. /**
  27. * Find out the client's IP address from the headers available to us
  28. *
  29. * @param Request $request PSR-7 Request
  30. *
  31. * @return string
  32. */
  33. protected function determineClientIpAddress(Request $request): string
  34. {
  35. $ipAddress = '';
  36.  
  37. $serverParams = $request->getServerParams();
  38. if (isset($serverParams['REMOTE_ADDR'])) {
  39. $remoteAddr = $this->extractIpAddress($serverParams['REMOTE_ADDR']);
  40. if ($this->isValidIpAddress($remoteAddr)) {
  41. $ipAddress = $remoteAddr;
  42. }
  43. }
  44.  
  45. return $ipAddress;
  46. }
  47.  
  48. /**
  49. * Remove port from IPV4 address if it exists
  50. *
  51. * Note: leaves IPV6 addresses alone
  52. *
  53. * @param string $ipAddress
  54. * @return string
  55. */
  56. protected function extractIpAddress(string $ipAddress): string
  57. {
  58. $parts = explode(':', $ipAddress);
  59.  
  60. if (count($parts) === 2) {
  61. if (filter_var($parts[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
  62. return $parts[0];
  63. }
  64. }
  65.  
  66. return $ipAddress;
  67. }
  68.  
  69. /**
  70. * Check that a given string is a valid IP address
  71. *
  72. * @param string $ip
  73. *
  74. * @return bool
  75. */
  76. protected function isValidIpAddress(string $ip): bool
  77. {
  78. $flags = FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6;
  79.  
  80. return filter_var($ip, FILTER_VALIDATE_IP, $flags) !== false;
  81. }
  82. }