$max) { throw new ApiException('内容字段格式或长度不正确:'.$key); } return trim($value); } public static function integer(array $input, string $key, int $default, int $min, int $max): int { $value = $input[$key] ?? $default; if (filter_var($value, FILTER_VALIDATE_INT) === false || (int)$value < $min || (int)$value > $max) { throw new ApiException('内容数字字段不正确:'.$key); } return (int)$value; } public static function values(array $input): array { $values = []; foreach (['title' => 120, 'audience' => 30, 'region' => 80, 'image_url' => 500, 'target_url' => 500] as $key => $max) { $values[$key] = self::text($input, $key, $max); } if ($values['title'] === '') throw new ApiException('请填写内容标题'); if (!in_array($values['audience'], ['all', 'new', 'purchased', 'enterprise_admin'], true)) { throw new ApiException('投放人群不支持'); } if ($values['region'] === '全国') $values['region'] = ''; foreach (['image_url', 'target_url'] as $key) { $url = $values[$key]; if ($url !== '' && (!filter_var($url, FILTER_VALIDATE_URL) || !preg_match('#^https?://[^\s]+$#iD', $url))) { throw new ApiException('图片和活动链接必须是有效的 http 或 https 地址'); } } foreach (['starts_at', 'ends_at'] as $key) { $value = self::text($input, $key, 19); if ($value !== '') { if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/D', $value)) { throw new ApiException('活动时间格式不正确'); } $date = \DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $value, new \DateTimeZone('Asia/Shanghai')); if (!$date || $date->format('Y-m-d H:i:s') !== $value || $value < '2000-01-01 00:00:00') { throw new ApiException('活动时间不正确,请选择2000年之后的日期'); } } $values[$key] = $value === '' ? null : $value; } if ($values['starts_at'] && $values['ends_at'] && $values['starts_at'] >= $values['ends_at']) { throw new ApiException('结束时间必须晚于开始时间'); } $values['status'] = self::integer($input, 'status', 1, 1, 2); $values['sort'] = self::integer($input, 'sort', 0, 0, 10000000); return $values; } }