72 lines
2.7 KiB
PHP
72 lines
2.7 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
namespace app\service;
|
|
|
|
use app\exception\ApiError;
|
|
|
|
final class Input
|
|
{
|
|
public static function only(array $data, array $allowed): void
|
|
{
|
|
if (array_diff(array_keys($data), $allowed) !== []) {
|
|
throw new ApiError(422, '请求包含不支持的字段');
|
|
}
|
|
}
|
|
|
|
public static function text(mixed $value, string $label, int $min = 1, int $max = 64): string
|
|
{
|
|
if (!is_string($value)) {
|
|
throw new ApiError(422, $label . '格式错误');
|
|
}
|
|
$value = trim($value);
|
|
if (mb_strlen($value) < $min || mb_strlen($value) > $max || preg_match('/[\x00-\x1f\x7f]/', $value)) {
|
|
throw new ApiError(422, $label . '长度或格式错误');
|
|
}
|
|
return $value;
|
|
}
|
|
|
|
public static function integer(mixed $value, string $label = 'id', int $min = 1, int $max = PHP_INT_MAX): int
|
|
{
|
|
if ((!is_int($value) && !(is_string($value) && preg_match('/^(0|[1-9][0-9]*)$/D', $value)))
|
|
|| filter_var($value, FILTER_VALIDATE_INT) === false || (int) $value < $min || (int) $value > $max) {
|
|
throw new ApiError(422, $label . '必须是有效整数');
|
|
}
|
|
return (int) $value;
|
|
}
|
|
|
|
public static function ids(mixed $value, string $label): array
|
|
{
|
|
if (!is_array($value) || !array_is_list($value) || count($value) > 500) {
|
|
throw new ApiError(422, $label . '必须是有效编号数组(最多500项)');
|
|
}
|
|
return array_values(array_unique(array_map(static fn ($id) => self::integer($id, $label), $value)));
|
|
}
|
|
|
|
public static function password(mixed $value): string
|
|
{
|
|
if (!is_string($value) || strlen($value) < 10 || strlen($value) > 72 || str_contains($value, "\0")) {
|
|
throw new ApiError(422, '密码必须为10至72字节');
|
|
}
|
|
return $value;
|
|
}
|
|
|
|
public static function account(mixed $value): string
|
|
{
|
|
$value = self::text($value, '账号', 3, 64);
|
|
if (!preg_match('/^[a-zA-Z0-9_.@-]+$/D', $value)) {
|
|
throw new ApiError(422, '账号仅支持字母、数字和 _.@-');
|
|
}
|
|
return strtolower($value);
|
|
}
|
|
|
|
public static function page(array $query): array
|
|
{
|
|
self::only($query, ['page_no', 'page_size', 'keyword', 'disable']);
|
|
$page = self::integer($query['page_no'] ?? 1, '页码', 1, 1000000);
|
|
$size = min(100, self::integer($query['page_size'] ?? 20, '每页条数', 1, 1000000));
|
|
$keyword = self::text($query['keyword'] ?? '', '关键词', 0, 64);
|
|
$disable = isset($query['disable']) && $query['disable'] !== '' ? self::integer($query['disable'], '状态', 0, 1) : null;
|
|
return [$page, $size, $keyword, $disable];
|
|
}
|
|
}
|