CharController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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', 'Account']);
  194. // 4. Обновляем модель и возвращаем ответ
  195. return $this->_updateAndRespond($model, $data);
  196. }
  197. /**
  198. * Возвращает конфигурацию таблицы или null, если таблица не разрешена.
  199. *
  200. * @param string $table
  201. * @return array|null
  202. */
  203. private function resolveTable(string $table): ?array
  204. {
  205. return self::TABLES[$table] ?? null;
  206. }
  207. /**
  208. * Белый список доступных для обновления таблиц.
  209. * Используется в resolveTable(), GetCharacterData(), UpdateCharacterData().
  210. */
  211. private const TABLES = [
  212. 'CharBase' => ['key' => 'DBKey', 'model' => CharBase::class, 'pk' => 'DBKey'],
  213. 'CharItem' => ['key' => 'Owner', 'model' => CharItem::class, 'pk' => 'CharItemID'],
  214. 'CharFellow' => ['key' => 'Owner', 'model' => CharFellow::class, 'pk' => 'FellowID'],
  215. ];
  216. /**
  217. * Получить конкретный предмет по CharItemID.
  218. *
  219. * @param int $char_item_id
  220. * @return \Illuminate\Http\JsonResponse
  221. */
  222. public function GetCharItem(int $char_item_id)
  223. {
  224. $item = CharItem::find($char_item_id);
  225. if (!$item) {
  226. return response()->json([
  227. 'code' => -2,
  228. 'msg' => 'CharItem not found.'
  229. ], 404);
  230. }
  231. return response()->json([
  232. 'code' => 0,
  233. 'msg' => 'CharItem successfully received.',
  234. 'data' => $item,
  235. ], 200);
  236. }
  237. /**
  238. * Обновить конкретный предмет по CharItemID.
  239. *
  240. * @param \Illuminate\Http\Request $request
  241. * @param int $char_item_id
  242. * @return \Illuminate\Http\JsonResponse
  243. */
  244. public function UpdateCharItem(Request $request, int $char_item_id)
  245. {
  246. $item = CharItem::find($char_item_id);
  247. if (!$item) {
  248. return response()->json([
  249. 'code' => -2,
  250. 'msg' => 'CharItem not found.'
  251. ], 404);
  252. }
  253. // Определяем защищённые поля, которые нельзя обновлять
  254. $protected = ['CharItemID', 'Owner', 'Account'];
  255. $data = $request->except($protected);
  256. return $this->_updateAndRespond($item, $data, 'CharItem successfully updated.');
  257. }
  258. /**
  259. * Общий метод для обновления модели и формирования ответа.
  260. *
  261. * @param \Illuminate\Database\Eloquent\Model $model
  262. * @param array $data
  263. * @param string $successMsg
  264. * @return \Illuminate\Http\JsonResponse
  265. */
  266. private function _updateAndRespond(\Illuminate\Database\Eloquent\Model $model, array $data, string $successMsg = 'Data successfully updated.')
  267. {
  268. // 1. Фильтруем поля для массового присвоения
  269. $fillable = $model->getFillable();
  270. $guarded = $model->getGuarded();
  271. if (!empty($fillable)) {
  272. // Если есть fillable - используем только их
  273. $filteredData = array_intersect_key($data, array_flip($fillable));
  274. } elseif ($guarded === ['*']) {
  275. // Если guarded = ['*'] - запрещено массовое присвоение
  276. return response()->json(['code' => -6, 'msg' => 'Mass assignment is not allowed for this model.'], 400);
  277. } else {
  278. // Если есть guarded (но не ['*']) - исключаем только guarded поля
  279. $filteredData = array_diff_key($data, array_flip($guarded));
  280. }
  281. // 2. Конвертируем null-поля в '', чтобы вместо NULL в БД сохранялась пустая строка
  282. $filteredData = array_map(static fn ($v) => $v === null ? '' : $v, $filteredData);
  283. if (empty($filteredData)) {
  284. return response()->json(['code' => -6, 'msg' => 'No valid fields to update.'], 400);
  285. }
  286. // 3. Пытаемся обновить запись
  287. try {
  288. $ok = $model->update($filteredData);
  289. } catch (\Throwable $e) {
  290. return response()->json([
  291. 'code' => -7,
  292. 'msg' => 'Database error while updating record.',
  293. 'error' => $e->getMessage(),
  294. ], 500);
  295. }
  296. if (!$ok) {
  297. return response()->json([
  298. 'code' => -8,
  299. 'msg' => 'Update failed, record not modified.',
  300. ], 500);
  301. }
  302. // 4. Возвращаем успешный ответ
  303. return response()->json([
  304. 'code' => 0,
  305. 'msg' => $successMsg,
  306. 'data' => $model->fresh()
  307. ], 200);
  308. }
  309. }