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/Models/Shop.php

84 lines
3.3 KiB
PHP

<?php
namespace App\Models;
class Shop extends Model
{
public const GIB = 1073741824;
protected $connection = 'default';
protected $table = 'shop';
protected $casts = [
'host_id' => '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;
}
}