| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141 |
- <?php
- namespace App\Module\Transfer\Validators;
- use App\Module\Transfer\Models\TransferApp;
- use App\Module\Transfer\Models\TransferOrder;
- use UCore\Validation\ValidatorCore;
- /**
- * 业务ID验证器
- */
- class BusinessIdValidator extends ValidatorCore
- {
- private string $businessId;
- private int $appId;
- public function __construct(string $businessId, int $appId)
- {
- $this->businessId = $businessId;
- $this->appId = $appId;
- }
- /**
- * 执行验证
- */
- public function validate(): bool
- {
- // 验证业务ID格式
- if (!$this->validateFormat()) {
- return false;
- }
- // 验证业务ID唯一性
- if (!$this->validateUniqueness()) {
- return false;
- }
- return true;
- }
- /**
- * 验证业务ID格式
- */
- private function validateFormat(): bool
- {
- // 检查长度
- if (strlen($this->businessId) < 3) {
- $this->addError('业务ID长度不能少于3个字符');
- return false;
- }
- if (strlen($this->businessId) > 100) {
- $this->addError('业务ID长度不能超过100个字符');
- return false;
- }
- // 检查字符格式(只允许字母、数字、下划线、中划线)
- if (!preg_match('/^[a-zA-Z0-9_-]+$/', $this->businessId)) {
- $this->addError('业务ID只能包含字母、数字、下划线和中划线');
- return false;
- }
- // 检查是否以字母或数字开头
- if (!preg_match('/^[a-zA-Z0-9]/', $this->businessId)) {
- $this->addError('业务ID必须以字母或数字开头');
- return false;
- }
- // 检查是否包含连续的特殊字符
- if (preg_match('/[_-]{2,}/', $this->businessId)) {
- $this->addError('业务ID不能包含连续的下划线或中划线');
- return false;
- }
- return true;
- }
- /**
- * 验证业务ID唯一性
- */
- private function validateUniqueness(): bool
- {
- // 获取应用配置
- $app = TransferApp::find($this->appId);
- if (!$app) {
- $this->addError('应用不存在');
- return false;
- }
- // 检查是否已存在相同的业务ID
- $existingOrder = TransferOrder::where('out_order_id', $this->businessId)
- ->where('out_id', $app->out_id)
- ->first();
- if ($existingOrder) {
- $this->addError('业务ID已存在');
- return false;
- }
- return true;
- }
- /**
- * 生成建议的业务ID
- */
- public function generateSuggestion(): string
- {
- $prefix = 'TR';
- $timestamp = date('YmdHis');
- $random = strtoupper(substr(md5(uniqid()), 0, 6));
-
- return $prefix . $timestamp . $random;
- }
- /**
- * 验证业务ID是否可用
- */
- public static function isAvailable(string $businessId, int $appId): bool
- {
- $validator = new self($businessId, $appId);
- return $validator->validate();
- }
- /**
- * 批量验证业务ID
- */
- public static function validateBatch(array $businessIds, int $appId): array
- {
- $results = [];
-
- foreach ($businessIds as $businessId) {
- $validator = new self($businessId, $appId);
- $results[$businessId] = [
- 'valid' => $validator->validate(),
- 'error' => $validator->getError()
- ];
- }
-
- return $results;
- }
- }
|