You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudPublicNetworkAddressPo...

85 lines
2.9 KiB
PHP

<?php
namespace App\Services\Cloud;
/** Pure address identity and selectability policy for a persisted pool. */
final class CloudPublicNetworkAddressPolicy
{
public static function contract(
object $pool,
?int $expectedFamily = null
): CloudPublicIpPoolContract {
$contract = CloudPublicIpPoolContract::fromRow($pool);
if ($expectedFamily !== null
&& $contract->family() !== $expectedFamily) {
throw new \InvalidArgumentException(
'Public IP pool family does not match.'
);
}
return $contract;
}
/** Validate immutable row identity without applying mutable exclusions. */
public static function assertIdentity(
object $row,
object $pool,
CloudPublicIpPoolContract $contract
): CloudIpAddress {
$address = CloudIpAddress::parse((string) ($row->address ?? ''));
if ((int) ($row->host_id ?? 0) !== (int) ($pool->host_id ?? 0)
|| (int) ($row->public_ip_pool_id ?? 0)
!== (int) ($pool->id ?? 0)
|| (int) ($row->address_family ?? 0)
!== (int) ($pool->address_family ?? 0)
|| $contract->family() !== (int) ($pool->address_family ?? 0)
|| (int) ($row->prefix_length ?? 0)
!== $contract->guestPrefixLength()
|| !hash_equals($address->text(), (string) $row->address)
|| !is_string($row->address_binary ?? null)
|| !hash_equals($address->binary(), $row->address_binary)
|| !$contract->addressBelongs($address)) {
throw new \InvalidArgumentException(
'Public IP address identity is invalid.'
);
}
return $address;
}
/** Validate an address row as a current allocation candidate. */
public static function assertSelectable(
object $row,
object $pool,
CloudPublicIpPoolContract $contract,
?string $managementAddress
): CloudIpAddress {
$address = self::assertIdentity($row, $pool, $contract);
if (!self::addressSelectable(
$address,
$contract,
$managementAddress
)) {
throw new \InvalidArgumentException(
'Public IP address is not selectable.'
);
}
return $address;
}
public static function addressSelectable(
CloudIpAddress $address,
CloudPublicIpPoolContract $contract,
?string $managementAddress
): bool {
if (!$contract->addressAllowed($address)) {
return false;
}
$managementAddress = trim((string) $managementAddress);
if ($managementAddress === '') {
return true;
}
$management = CloudIpAddress::parse($managementAddress);
return $management->family() !== $address->family()
|| !$management->equals($address);
}
}