CharController.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. $config = $this->resolveTable($table_name);
  137. if (!$config) {
  138. return response()->json(['code' => -1, 'msg' => 'Table not allowed or does not exist.'], 400);
  139. }
  140. $modelClass = $config['model'];
  141. $key = $config['key'];
  142. // Проверяем существование персонажа
  143. if (!CharBase::find($char_id)) {
  144. return response()->json(['code' => -2, 'msg' => 'Character not found.'], 404);
  145. }
  146. // Получаем данные
  147. $data = $modelClass::where($key, $char_id)->get();
  148. if ($data->isEmpty()) {
  149. return response()->json(['code' => -3, 'msg' => 'No data found for this character in the specified table.'], 200);
  150. }
  151. return response()->json([
  152. 'code' => 0,
  153. 'msg' => 'Data successfully received.',
  154. 'data' => $data
  155. ], 200);
  156. }
  157. /**
  158. * Обновление данных персонажа в указанной таблице.
  159. *
  160. * @param Request $request
  161. * @param int $char_id
  162. * @param string $table_name
  163. * @return \Illuminate\Http\JsonResponse
  164. */
  165. public function UpdateCharacterData(Request $request, $char_id, $table_name)
  166. {
  167. // 1. Получаем конфигурацию таблицы из константы
  168. $config = $this->resolveTable($table_name);
  169. if (!$config) {
  170. return response()->json(['code' => -1, 'msg' => 'Table not allowed or does not exist.'], 400);
  171. }
  172. $modelClass = $config['model'];
  173. $ownerKey = $config['key'];
  174. $primaryKey = $config['pk'];
  175. // 2. Определяем, какую запись обновляем
  176. if ($table_name === 'CharBase') {
  177. $model = $modelClass::find($char_id);
  178. } else {
  179. $recordId = $request->input($primaryKey);
  180. if (!$recordId) {
  181. return response()->json(['code' => -4, 'msg' => "Primary key '$primaryKey' is required for this table."], 400);
  182. }
  183. $model = $modelClass::find($recordId);
  184. }
  185. if (!$model) {
  186. return response()->json(['code' => -2, 'msg' => 'Record not found.'], 404);
  187. }
  188. // Проверяем принадлежность записи персонажу
  189. if ($model->{$ownerKey} != $char_id) {
  190. return response()->json(['code' => -5, 'msg' => 'Record does not belong to the character.'], 403);
  191. }
  192. // 3. Подготавливаем данные к обновлению – защищаем PK и владение
  193. $data = $request->except([$primaryKey, $ownerKey, 'DBKey', 'Owner']);
  194. // 4. Фильтруем только разрешённые к массовому присвоению поля
  195. $fillable = $model->getFillable();
  196. $filteredData = array_intersect_key($data, array_flip($fillable));
  197. if (empty($filteredData)) {
  198. return response()->json(['code' => -6, 'msg' => 'No valid fields to update.'], 400);
  199. }
  200. // 5. Обновляем запись и возвращаем свежие данные
  201. $model->update($filteredData);
  202. return response()->json([
  203. 'code' => 0,
  204. 'msg' => 'Data successfully updated.',
  205. 'data' => $model->fresh()
  206. ], 200);
  207. }
  208. /**
  209. * Возвращает конфигурацию таблицы или null, если таблица не разрешена.
  210. *
  211. * @param string $table
  212. * @return array|null
  213. */
  214. private function resolveTable(string $table): ?array
  215. {
  216. return self::TABLES[$table] ?? null;
  217. }
  218. /**
  219. * Белый список доступных для обновления таблиц.
  220. * Используется в resolveTable(), GetCharacterData(), UpdateCharacterData().
  221. */
  222. private const TABLES = [
  223. 'CharBase' => ['key' => 'DBKey', 'model' => CharBase::class, 'pk' => 'DBKey'],
  224. 'CharItem' => ['key' => 'Owner', 'model' => CharItem::class, 'pk' => 'CharItemID'],
  225. 'CharFellow' => ['key' => 'Owner', 'model' => CharFellow::class, 'pk' => 'FellowID'],
  226. ];
  227. }