| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192 |
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use App\Models\Char\CharBase;
- use App\Models\Char\CharCashItem_OutputBox;
- use App\Models\Char\CharItem;
- use App\Models\Char\CharFellow;
- class CharController extends Controller
- {
- /**
- * Получение всех персонажей из базы данных с пагинацией.
- * *
- * @return \Illuminate\Http\JsonResponse
- */
- public function GetAllCharacters(Request $request)
- {
- // 1. Валидация и параметры запроса
- $validated = $request->validate([
- 'per_page' => 'sometimes|integer|min:1|max:100',
- 'search' => 'sometimes|string|nullable|max:50',
- ]);
- $perPage = $validated['per_page'] ?? 15;
- $search = trim($validated['search'] ?? '');
- $sortField = $request->input('sort_field', 'DBKey');
- $sortOrder = strtolower($request->input('sort_order', 'asc')) === 'desc' ? 'desc' : 'asc';
- // whitelist для полей сортировки и выборки
- $allowedSortFields = ['DBKey', 'Name', 'Level', 'AccountName'];
- if (!in_array($sortField, $allowedSortFields, true)) {
- $sortField = 'DBKey';
- }
- // 2. Запрос с выборкой только нужных полей
- $query = CharBase::query()->select($allowedSortFields);
- if ($search !== '') {
- $query->where(function ($q) use ($search) {
- $q->where('Name', 'like', "%{$search}%")
- ->orWhere('AccountName', 'like', "%{$search}%");
- if (ctype_digit($search)) {
- $q->orWhere('DBKey', (int) $search);
- }
- });
- }
- // 3. Сортировка и пагинация
- $charactersPaginator = $query->orderBy($sortField, $sortOrder)->paginate($perPage);
- // 4. Ответ
- // Если по запросу не найдено ни одного персонажа, возвращаем специальный ответ
- // для сохранения обратной совместимости API.
- if ($charactersPaginator->total() === 0) {
- return response()->json([
- 'characters' => (object) [],
- 'code' => -2,
- 'msg' => 'Characters not found.'
- ], 200);
- }
- // Laravel автоматически преобразует пагинатор в корректный JSON,
- // включая только выбранные через select() поля.
- return response()->json([
- 'code' => 0,
- 'msg' => 'Characters successfully received.',
- 'characters' => $charactersPaginator,
- ], 200);
- }
-
- /**
- * Получение всех персонажей пользователя по AccountDBID.
- *
- * @param string $username
- * @return \Illuminate\Http\JsonResponse
- */
- public function GetUserCharacters($username)
- {
- // Получаем всех персонажей по $username
- $characters = CharBase::where('AccountName', $username)->get();
- // Проверяем, найдены ли персонажи
- if ($characters->isEmpty()) {
- return response()->json(['characters' => [], 'code' => -2, 'msg' => 'Characters not found for this user.'], 200);
- }
- // Подсчитываем общее время в игре для всех персонажей пользователя
- $totalPlayTime = $characters->sum('TotalPlayTime');
- // Возвращаем только DBKey, Name, Level, GuildDBKey, TotalPlayTime персонажей
- $characters = $characters->map(function ($character) {
- return [
- 'DBKey' => $character->DBKey,
- 'Name' => $character->Name,
- 'Level' => $character->Level,
- 'GuildDBKey' => $character->GuildDBKey,
- 'CharPlayTime' => $character->TotalPlayTime
- ];
- });
- return response()->json([
- 'code' => 0,
- 'msg' => 'Characters successfully received.',
- 'characters' => $characters,
- 'totalPlayTime' => $totalPlayTime
- ], 200);
- }
- public function SendItemToCharacter(Request $request)
- {
- $character = CharBase::where('DBKey', $request->Owner)->first();
- if (!$character) {
- return response()->json(['code' => -1, 'msg' => 'Character not found.'], 404);
- }
- $validator = \Validator::make($request->all(), [
- 'Owner' => 'required',
- 'Kind' => 'required',
- 'RecId' => 'required',
- 'Amount' => 'required|numeric',
- 'Period' => 'required|numeric',
- 'evPType' => 'required',
- 'Comment' => 'required'
- ], [], [
- 'Owner' => '',
- 'Kind' => '',
- 'RecId' => '',
- 'Amount' => '',
- 'Period' => '',
- 'evPType' => '',
- 'Comment' => ''
- ]);
- if (!$validator->passes())
- return response()->json(['code' => -1, 'msg' => $validator->errors()], 400);
- CharCashItem_OutputBox::SENDITEMOUTPUTBOX($request);
- return response()->json([
- 'code' => 0,
- 'msg' => 'Items successfully sent.'
- ], 200);
- }
- /**
- * Получение всех данных персонажа из указанной таблицы.
- *
- * @param int $char_id
- * @param string $table_name
- * @return \Illuminate\Http\JsonResponse
- */
- public function GetCharacterData($char_id, $table_name)
- {
- // Белый список доступных моделей/таблиц
- $allowed_tables = [
- 'CharBase' => ['key' => 'DBKey', 'model' => CharBase::class],
- 'CharItem' => ['key' => 'Owner', 'model' => CharItem::class],
- 'CharFellow' => ['key' => 'Owner', 'model' => CharFellow::class],
- ];
- if (!array_key_exists($table_name, $allowed_tables)) {
- return response()->json(['code' => -1, 'msg' => 'Table not allowed or does not exist.'], 400);
- }
- $modelClass = $allowed_tables[$table_name]['model'];
- $key = $allowed_tables[$table_name]['key'];
- // Проверка, существует ли персонаж в CharBase
- $character = CharBase::find($char_id);
- if (!$character) {
- return response()->json(['code' => -2, 'msg' => 'Character not found.'], 404);
- }
- $data = $modelClass::where($key, $char_id)->get();
- if ($data->isEmpty()) {
- return response()->json(['code' => -3, 'msg' => 'No data found for this character in the specified table.'], 200);
- }
- return response()->json([
- 'code' => 0,
- 'msg' => 'Data successfully received.',
- 'data' => $data
- ], 200);
- }
- }
|