IpsRequestMatcher.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\RequestMatcher;
  11. use Symfony\Component\HttpFoundation\IpUtils;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\RequestMatcherInterface;
  14. /**
  15. * Checks the client IP of a Request.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class IpsRequestMatcher implements RequestMatcherInterface
  20. {
  21. private array $ips;
  22. /**
  23. * @param string[]|string $ips A specific IP address or a range specified using IP/netmask like 192.168.1.0/24
  24. * Strings can contain a comma-delimited list of IPs/ranges
  25. */
  26. public function __construct(array|string $ips)
  27. {
  28. $this->ips = array_reduce((array) $ips, static fn (array $ips, string $ip) => array_merge($ips, preg_split('/\s*,\s*/', $ip)), []);
  29. }
  30. public function matches(Request $request): bool
  31. {
  32. if (!$this->ips) {
  33. return true;
  34. }
  35. return IpUtils::checkIp($request->getClientIp() ?? '', $this->ips);
  36. }
  37. }