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.
66 lines
2.6 KiB
PHP
66 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
class Shop extends Model
|
|
{
|
|
protected $connection = 'default';
|
|
protected $table = 'shop';
|
|
|
|
protected $casts = [
|
|
'host_id' => 'int',
|
|
'cpu_cores' => 'int', 'memory_mib' => 'int', 'bandwidth_mbps' => 'int',
|
|
'disk_gib' => 'int', 'status' => 'int', 'stock' => 'int', 'sort' => 'int',
|
|
'price' => 'decimal:2',
|
|
];
|
|
|
|
public function content()
|
|
{
|
|
return sprintf('%d 核 CPU · %d MiB 内存 · %d Mbps 带宽 · %d GiB 磁盘',
|
|
$this->cpu_cores, $this->memory_mib, $this->bandwidth_mbps, $this->disk_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],
|
|
'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;
|
|
}
|
|
$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;
|
|
}
|
|
}
|