1
0

Address.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 IPLib\ParseStringFlag;
  12. use OCP\Security\Ip\IAddress;
  13. use OCP\Security\Ip\IRange;
  14. /**
  15. * @since 30.0.0
  16. */
  17. class Address implements IAddress {
  18. private readonly AddressInterface $ip;
  19. public function __construct(string $ip) {
  20. $ip = Factory::parseAddressString($ip, ParseStringFlag::MAY_INCLUDE_ZONEID);
  21. if ($ip === null) {
  22. throw new InvalidArgumentException('Given IP address can’t be parsed');
  23. }
  24. $this->ip = $ip;
  25. }
  26. public static function isValid(string $ip): bool {
  27. return Factory::parseAddressString($ip, ParseStringFlag::MAY_INCLUDE_ZONEID) !== null;
  28. }
  29. public function matches(IRange ... $ranges): bool {
  30. foreach ($ranges as $range) {
  31. if ($range->contains($this)) {
  32. return true;
  33. }
  34. }
  35. return false;
  36. }
  37. public function __toString(): string {
  38. return $this->ip->toString();
  39. }
  40. }