'int', 'cpu_cores' => 'int', 'memory_mib' => 'int', 'bandwidth_mbps' => 'int', 'disk_gib' => 'int', 'validity_days' => 'int', 'traffic_quota_bytes' => 'int', 'status' => 'int', 'stock' => 'int', 'sort' => 'int', 'price' => 'decimal:2', ]; public function content() { return sprintf('%d 核 CPU · %d MiB 内存 · %d Mbps 带宽 · %d GiB 磁盘 · %d 天 · %s', $this->cpu_cores, $this->memory_mib, $this->bandwidth_mbps, $this->disk_gib, $this->validity_days, $this->trafficQuotaText()); } public function trafficGiB(): int { return intdiv(max(0, (int) $this->traffic_quota_bytes), self::GIB); } public function trafficQuotaText(): string { return (int) $this->traffic_quota_bytes === 0 ? '不限流量' : $this->trafficGiB() . ' GiB 流量'; } public static function validatePlan(array $input): array { $name = isset($input['name']) && is_string($input['name']) ? trim($input['name']) : ''; if ($name === '' || mb_strlen($name) > 128) { throw new \InvalidArgumentException('套餐名称需为 1 至 128 个字符'); } $data = ['name' => $name]; $host = $input['host_id'] ?? null; if ($host === null || $host === '') { $data['host_id'] = null; } else { $host = filter_var($host, FILTER_VALIDATE_INT); if ($host === false || $host < 1) { throw new \InvalidArgumentException('请选择有效的宿主机'); } $data['host_id'] = $host; } foreach ([ 'cpu_cores' => [1, 64], 'memory_mib' => [512, 262144], 'bandwidth_mbps' => [1, 100000], 'disk_gib' => [1, 4096], 'validity_days' => [1, 3650], 'traffic_gib' => [0, 1048576], 'status' => [0, 1], 'stock' => [-1, 2147483647], 'sort' => [-1000000, 1000000], ] as $field => [$minimum, $maximum]) { $raw = $input[$field] ?? (['status' => 1, 'stock' => -1, 'sort' => 0][$field] ?? null); $value = is_string($raw) || is_int($raw) ? filter_var($raw, FILTER_VALIDATE_INT) : false; if ($value === false || $value < $minimum || $value > $maximum) { throw new \InvalidArgumentException($field . ' 需为 ' . $minimum . ' 至 ' . $maximum . ' 的整数'); } $data[$field] = $value; } $trafficGiB = $data['traffic_gib']; unset($data['traffic_gib']); $data['traffic_quota_bytes'] = $trafficGiB * self::GIB; $price = $input['price'] ?? ''; if ((!is_string($price) && !is_int($price)) || preg_match('/^\d{1,10}(?:\.\d{1,2})?$/D', (string) $price) !== 1) { throw new \InvalidArgumentException('价格需为非负金额,最多两位小数'); } $parts = explode('.', (string) $price); $data['price'] = ltrim($parts[0], '0'); if ($data['price'] === '') { $data['price'] = '0'; } $data['price'] .= '.' . str_pad($parts[1] ?? '', 2, '0'); return $data; } }