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/CloudOffer.php

97 lines
3.3 KiB
PHP

<?php
namespace App\Models;
final class CloudOffer extends Model
{
protected $connection = 'default';
protected $table = 'cloud_offers';
protected $casts = [
'id' => 'int',
'plan_id' => 'int',
'resource_pool_id' => 'int',
'price' => 'decimal:2',
'backup_price' => 'decimal:2',
'price_version' => 'int',
'revision' => 'int',
'status' => 'boolean',
'stock' => 'int',
'sort' => 'int',
'created_at' => 'int',
'updated_at' => 'int',
];
public static function generateSystemCode(): string
{
return 'offer-' . bin2hex(random_bytes(16));
}
public static function validateOffer(array $input): array
{
$poolId = filter_var($input['resource_pool_id'] ?? null, FILTER_VALIDATE_INT);
if ($poolId === false || $poolId < 1) {
throw new \InvalidArgumentException('请选择有效的销售位置');
}
$code = isset($input['code']) && is_string($input['code'])
? trim($input['code']) : '';
if (preg_match('/^[a-z0-9][a-z0-9_-]{0,63}$/D', $code) !== 1) {
throw new \InvalidArgumentException('销售方案系统标识需为 1 至 64 位小写字母、数字、下划线或连字符');
}
$name = isset($input['name']) && is_string($input['name']) ? trim($input['name']) : '';
if ($name === '' || mb_strlen($name) > 128) {
throw new \InvalidArgumentException('销售名称需为 1 至 128 个字符');
}
$normalizedPrice = self::normalizePrice(
$input['price'] ?? '',
'实例价格'
);
$normalizedBackupPrice = self::normalizePrice(
$input['backup_price'] ?? '',
'自动备份价格'
);
$data = [
'resource_pool_id' => (int) $poolId,
'code' => $code,
'name' => $name,
'price' => $normalizedPrice,
'backup_price' => $normalizedBackupPrice,
'currency' => 'USD',
];
foreach ([
'status' => [0, 1, 1, '销售状态'],
'stock' => [-1, 2147483647, -1, '库存'],
'sort' => [-1000000, 1000000, 0, '排序'],
] as $field => [$minimum, $maximum, $default, $label]) {
$raw = $input[$field] ?? $default;
$value = is_string($raw) || is_int($raw)
? filter_var($raw, FILTER_VALIDATE_INT) : false;
if ($value === false || $value < $minimum || $value > $maximum) {
throw new \InvalidArgumentException(
$label . ' 需为 ' . $minimum . ' 至 ' . $maximum . ' 的整数'
);
}
$data[$field] = (int) $value;
}
return $data;
}
private static function normalizePrice($value, string $label): string
{
if ((!is_string($value) && !is_int($value))
|| preg_match('/^\d{1,10}(?:\.\d{1,2})?$/D', (string) $value) !== 1) {
throw new \InvalidArgumentException(
$label . '需为非负美元金额,最多两位小数'
);
}
$parts = explode('.', (string) $value);
$whole = ltrim($parts[0], '0');
return ($whole === '' ? '0' : $whole) . '.'
. str_pad($parts[1] ?? '', 2, '0');
}
}