aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Security/Ip/Address.php
blob: b4f12a7e295feaa004b28395898e4e14e5e49b56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php

declare(strict_types=1);
/**
 * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OC\Security\Ip;

use InvalidArgumentException;
use IPLib\Address\AddressInterface;
use IPLib\Factory;
use OCP\Security\Ip\IAddress;
use OCP\Security\Ip\IRange;

/**
 * @since 30.0.0
 */
class Address implements IAddress {
	private readonly AddressInterface $ip;

	public function __construct(string $ip) {
		$ip = Factory::parseAddressString($ip);
		if ($ip === null) {
			throw new InvalidArgumentException('Given IP address can’t be parsed');
		}
		$this->ip = $ip;
	}

	public static function isValid(string $ip): bool {
		return Factory::parseAddressString($ip) !== null;
	}

	public function matches(IRange... $ranges): bool {
		foreach($ranges as $range) {
			if ($range->contains($this)) {
				return true;
			}
		}

		return false;
	}

	public function __toString(): string {
		return $this->ip->toString();
	}
}