79 lines
2.1 KiB
PHP
79 lines
2.1 KiB
PHP
|
<?php
|
||
|
declare(strict_types=1);
|
||
|
|
||
|
// 参数验证函数
|
||
|
function validateRequestParams(): array {
|
||
|
$allowedResolutions = ['UHD', '4K', 'HD'];
|
||
|
$allowedCategories = ['美女', '风景', '动物', '游戏'];
|
||
|
|
||
|
// 获取并处理参数
|
||
|
$params = [
|
||
|
'resolution' => isset($_GET['resolution'])
|
||
|
? strtoupper(trim($_GET['resolution']))
|
||
|
: null,
|
||
|
'category' => isset($_GET['category'])
|
||
|
? urldecode(trim($_GET['category']))
|
||
|
: null
|
||
|
];
|
||
|
|
||
|
// 验证分辨率参数
|
||
|
if ($params['resolution'] && !in_array($params['resolution'], $allowedResolutions, true)) {
|
||
|
throw new InvalidArgumentException('无效的分辨率参数');
|
||
|
}
|
||
|
|
||
|
// 验证分类参数
|
||
|
if ($params['category'] && !in_array($params['category'], $allowedCategories, true)) {
|
||
|
throw new InvalidArgumentException('无效的分类参数');
|
||
|
}
|
||
|
|
||
|
return $params;
|
||
|
}
|
||
|
|
||
|
// 构建图片查询语句
|
||
|
function buildImageQuery(array $params): string {
|
||
|
$query = "SELECT url FROM images WHERE 1=1";
|
||
|
|
||
|
if ($params['resolution']) {
|
||
|
$query .= " AND resolution = :resolution";
|
||
|
}
|
||
|
|
||
|
if ($params['category']) {
|
||
|
$query .= " AND category = :category";
|
||
|
}
|
||
|
|
||
|
$query .= " ORDER BY RAND() LIMIT 1";
|
||
|
return $query;
|
||
|
}
|
||
|
|
||
|
// 获取随机图片
|
||
|
function fetchRandomImage(PDO $pdo, string $query, array $params) {
|
||
|
$stmt = $pdo->prepare($query);
|
||
|
|
||
|
if ($params['resolution']) {
|
||
|
$stmt->bindValue(':resolution', $params['resolution']);
|
||
|
}
|
||
|
|
||
|
if ($params['category']) {
|
||
|
$stmt->bindValue(':category', $params['category']);
|
||
|
}
|
||
|
|
||
|
$stmt->execute();
|
||
|
return $stmt->fetch();
|
||
|
}
|
||
|
|
||
|
// 标准化JSON响应
|
||
|
function jsonResponse(array $data): string {
|
||
|
return json_encode([
|
||
|
'code' => 200,
|
||
|
'data' => $data
|
||
|
], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
|
||
|
}
|
||
|
|
||
|
// 错误响应格式化
|
||
|
function jsonError(string $message, int $code = 400): string {
|
||
|
http_response_code($code);
|
||
|
return json_encode([
|
||
|
'code' => $code,
|
||
|
'error' => $message
|
||
|
], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
|
||
|
}
|