| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- <?php
- declare(strict_types=1);
- namespace plugin\saiadmin\app\service\content;
- use plugin\saiadmin\exception\ApiException;
- /** Validated content configuration shared by every save entry point. */
- final class ContentInput
- {
- public static function text(array $input, string $key, int $max, string $default = ''): string
- {
- $value = $input[$key] ?? $default;
- if (!is_string($value) || mb_strlen($value) > $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;
- }
- }
|