CharController.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use App\Models\Char\CharBase;
  5. use App\Models\Char\CharCashItem_OutputBox;
  6. use App\Models\Char\CharItem;
  7. use App\Models\Char\CharFellow;
  8. class CharController extends Controller
  9. {
  10. /**
  11. * Получение всех персонажей из базы данных с пагинацией.
  12. * *
  13. * @return \Illuminate\Http\JsonResponse
  14. */
  15. public function GetAllCharacters(Request $request)
  16. {
  17. // 1. Валидация и параметры запроса
  18. $validated = $request->validate([
  19. 'per_page' => 'sometimes|integer|min:1|max:100',
  20. 'search' => 'sometimes|string|nullable|max:50',
  21. ]);
  22. $perPage = $validated['per_page'] ?? 15;
  23. $search = trim($validated['search'] ?? '');
  24. $sortField = $request->input('sort_field', 'DBKey');
  25. $sortOrder = strtolower($request->input('sort_order', 'asc')) === 'desc' ? 'desc' : 'asc';
  26. // whitelist для полей сортировки и выборки
  27. $allowedSortFields = ['DBKey', 'Name', 'Level', 'AccountName'];
  28. if (!in_array($sortField, $allowedSortFields, true)) {
  29. $sortField = 'DBKey';
  30. }
  31. // 2. Запрос с выборкой только нужных полей
  32. $query = CharBase::query()->select($allowedSortFields);
  33. if ($search !== '') {
  34. $query->where(function ($q) use ($search) {
  35. $q->where('Name', 'like', "%{$search}%")
  36. ->orWhere('AccountName', 'like', "%{$search}%");
  37. if (ctype_digit($search)) {
  38. $q->orWhere('DBKey', (int) $search);
  39. }
  40. });
  41. }
  42. // 3. Сортировка и пагинация
  43. $charactersPaginator = $query->orderBy($sortField, $sortOrder)->paginate($perPage);
  44. // 4. Ответ
  45. // Если по запросу не найдено ни одного персонажа, возвращаем специальный ответ
  46. // для сохранения обратной совместимости API.
  47. if ($charactersPaginator->total() === 0) {
  48. return response()->json([
  49. 'characters' => (object) [],
  50. 'code' => -2,
  51. 'msg' => 'Characters not found.'
  52. ], 200);
  53. }
  54. // Laravel автоматически преобразует пагинатор в корректный JSON,
  55. // включая только выбранные через select() поля.
  56. return response()->json([
  57. 'code' => 0,
  58. 'msg' => 'Characters successfully received.',
  59. 'characters' => $charactersPaginator,
  60. ], 200);
  61. }
  62. /**
  63. * Получение всех персонажей пользователя по AccountDBID.
  64. *
  65. * @param string $username
  66. * @return \Illuminate\Http\JsonResponse
  67. */
  68. public function GetUserCharacters($username)
  69. {
  70. // Получаем всех персонажей по $username
  71. $characters = CharBase::where('AccountName', $username)->get();
  72. // Проверяем, найдены ли персонажи
  73. if ($characters->isEmpty()) {
  74. return response()->json(['characters' => [], 'code' => -2, 'msg' => 'Characters not found for this user.'], 200);
  75. }
  76. // Подсчитываем общее время в игре для всех персонажей пользователя
  77. $totalPlayTime = $characters->sum('TotalPlayTime');
  78. // Возвращаем только DBKey, Name, Level, GuildDBKey, TotalPlayTime персонажей
  79. $characters = $characters->map(function ($character) {
  80. return [
  81. 'DBKey' => $character->DBKey,
  82. 'Name' => $character->Name,
  83. 'Level' => $character->Level,
  84. 'GuildDBKey' => $character->GuildDBKey,
  85. 'CharPlayTime' => $character->TotalPlayTime
  86. ];
  87. });
  88. return response()->json([
  89. 'code' => 0,
  90. 'msg' => 'Characters successfully received.',
  91. 'characters' => $characters,
  92. 'totalPlayTime' => $totalPlayTime
  93. ], 200);
  94. }
  95. public function SendItemToCharacter(Request $request)
  96. {
  97. $character = CharBase::where('DBKey', $request->Owner)->first();
  98. if (!$character) {
  99. return response()->json(['code' => -1, 'msg' => 'Character not found.'], 404);
  100. }
  101. $validator = \Validator::make($request->all(), [
  102. 'Owner' => 'required',
  103. 'Kind' => 'required',
  104. 'RecId' => 'required',
  105. 'Amount' => 'required|numeric',
  106. 'Period' => 'required|numeric',
  107. 'evPType' => 'required',
  108. 'Comment' => 'required'
  109. ], [], [
  110. 'Owner' => '',
  111. 'Kind' => '',
  112. 'RecId' => '',
  113. 'Amount' => '',
  114. 'Period' => '',
  115. 'evPType' => '',
  116. 'Comment' => ''
  117. ]);
  118. if (!$validator->passes())
  119. return response()->json(['code' => -1, 'msg' => $validator->errors()], 400);
  120. CharCashItem_OutputBox::SENDITEMOUTPUTBOX($request);
  121. return response()->json([
  122. 'code' => 0,
  123. 'msg' => 'Items successfully sent.'
  124. ], 200);
  125. }
  126. /**
  127. * Получение всех данных персонажа из указанной таблицы.
  128. *
  129. * @param int $char_id
  130. * @param string $table_name
  131. * @return \Illuminate\Http\JsonResponse
  132. */
  133. public function GetCharacterData($char_id, $table_name)
  134. {
  135. // Белый список доступных моделей/таблиц
  136. $allowed_tables = [
  137. 'CharBase' => ['key' => 'DBKey', 'model' => CharBase::class],
  138. 'CharItem' => ['key' => 'Owner', 'model' => CharItem::class],
  139. 'CharFellow' => ['key' => 'Owner', 'model' => CharFellow::class],
  140. ];
  141. if (!array_key_exists($table_name, $allowed_tables)) {
  142. return response()->json(['code' => -1, 'msg' => 'Table not allowed or does not exist.'], 400);
  143. }
  144. $modelClass = $allowed_tables[$table_name]['model'];
  145. $key = $allowed_tables[$table_name]['key'];
  146. // Проверка, существует ли персонаж в CharBase
  147. $character = CharBase::find($char_id);
  148. if (!$character) {
  149. return response()->json(['code' => -2, 'msg' => 'Character not found.'], 404);
  150. }
  151. $data = $modelClass::where($key, $char_id)->get();
  152. if ($data->isEmpty()) {
  153. return response()->json(['code' => -3, 'msg' => 'No data found for this character in the specified table.'], 200);
  154. }
  155. return response()->json([
  156. 'code' => 0,
  157. 'msg' => 'Data successfully received.',
  158. 'data' => $data
  159. ], 200);
  160. }
  161. }