Address.php 996 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Security\Ip;
  8. use InvalidArgumentException;
  9. use IPLib\Address\AddressInterface;
  10. use IPLib\Factory;
  11. use OCP\Security\Ip\IAddress;
  12. use OCP\Security\Ip\IRange;
  13. /**
  14. * @since 30.0.0
  15. */
  16. class Address implements IAddress {
  17. private readonly AddressInterface $ip;
  18. public function __construct(string $ip) {
  19. $ip = Factory::parseAddressString($ip);
  20. if ($ip === null) {
  21. throw new InvalidArgumentException('Given IP address can’t be parsed');
  22. }
  23. $this->ip = $ip;
  24. }
  25. public static function isValid(string $ip): bool {
  26. return Factory::parseAddressString($ip) !== null;
  27. }
  28. public function matches(IRange ... $ranges): bool {
  29. foreach ($ranges as $range) {
  30. if ($range->contains($this)) {
  31. return true;
  32. }
  33. }
  34. return false;
  35. }
  36. public function __toString(): string {
  37. return $this->ip->toString();
  38. }
  39. }