|
@@ -0,0 +1,84 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+namespace App\Http\Controllers;
|
|
|
+
|
|
|
+use Illuminate\Http\JsonResponse;
|
|
|
+use Illuminate\Http\Request;
|
|
|
+use Illuminate\Support\Facades\Redis;
|
|
|
+
|
|
|
+class EnumController extends Controller
|
|
|
+{
|
|
|
+ /**
|
|
|
+ * 获取枚举数据
|
|
|
+ *
|
|
|
+ * @param Request $request
|
|
|
+ * @return JsonResponse
|
|
|
+ */
|
|
|
+ public function getEnumData(Request $request): JsonResponse
|
|
|
+ {
|
|
|
+ $enumName = $request->input('enum');
|
|
|
+
|
|
|
+ if (empty($enumName)) {
|
|
|
+ return response()->json([
|
|
|
+ 'data' => [
|
|
|
+ 'items' => [],
|
|
|
+ 'msg' => '枚举名称不能为空',
|
|
|
+ 'status' => 400
|
|
|
+ ]
|
|
|
+ ]);
|
|
|
+ }
|
|
|
+
|
|
|
+ try {
|
|
|
+ // 构造完整的枚举类名
|
|
|
+ $enumClass = "App\\Enums\\{$enumName}";
|
|
|
+
|
|
|
+ // 检查类是否存在
|
|
|
+ if (!class_exists($enumClass)) {
|
|
|
+ return response()->json([
|
|
|
+ 'data' => [
|
|
|
+ 'items' => [],
|
|
|
+ 'msg' => "枚举类 {$enumName} 不存在",
|
|
|
+ 'status' => 404
|
|
|
+ ]
|
|
|
+ ]);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 从Redis缓存获取数据
|
|
|
+ $cacheKey = "enum:{$enumName}";
|
|
|
+ $enumData = Redis::get($cacheKey);
|
|
|
+
|
|
|
+ if (!$enumData) {
|
|
|
+ // 缓存不存在,获取枚举数据并转换格式
|
|
|
+ $rawData = $enumClass::all();
|
|
|
+ $items = [];
|
|
|
+ foreach ($rawData as $value => $label) {
|
|
|
+ $items[] = [
|
|
|
+ 'label' => $label,
|
|
|
+ 'value' => $value
|
|
|
+ ];
|
|
|
+ }
|
|
|
+
|
|
|
+ // 存入Redis缓存,设置过期时间为1天
|
|
|
+ Redis::setex($cacheKey, 86400, json_encode($items));
|
|
|
+ } else {
|
|
|
+ $items = json_decode($enumData, true);
|
|
|
+ }
|
|
|
+
|
|
|
+ return response()->json([
|
|
|
+ 'data' => [
|
|
|
+ 'items' => $items,
|
|
|
+ 'msg' => '',
|
|
|
+ 'status' => 0
|
|
|
+ ]
|
|
|
+ ]);
|
|
|
+ } catch (\Throwable $e) {
|
|
|
+ return response()->json([
|
|
|
+ 'data' => [
|
|
|
+ 'items' => [],
|
|
|
+ 'msg' => $e->getMessage(),
|
|
|
+ 'status' => 500
|
|
|
+ ]
|
|
|
+ ]);
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|