Egame.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. <?php
  2. namespace App\Http\Controllers\admin;
  3. use App\Constants\HttpStatus;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\EgameItem;
  6. use Exception;
  7. use Illuminate\Http\JsonResponse;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Validation\Rule;
  10. use Illuminate\Validation\ValidationException;
  11. class Egame extends Controller
  12. {
  13. private const FALLBACK_GAME_TYPE_NAMES = [
  14. 1 => '视讯',
  15. 2 => '电子',
  16. 3 => '彩票',
  17. 4 => '体育',
  18. 5 => '电竞',
  19. 6 => '捕鱼',
  20. 7 => '棋牌',
  21. ];
  22. public function items(): JsonResponse
  23. {
  24. try {
  25. request()->validate([
  26. 'item_type' => ['nullable', Rule::in([
  27. EgameItem::TYPE_CATEGORY,
  28. EgameItem::TYPE_PLATFORM,
  29. EgameItem::TYPE_GAME,
  30. ])],
  31. 'platform_scope' => ['nullable', Rule::in([
  32. EgameItem::PLATFORM_SCOPE_GLOBAL,
  33. EgameItem::PLATFORM_SCOPE_CATEGORY,
  34. ])],
  35. 'plat_type' => ['nullable', 'string', 'max:32'],
  36. 'game_type' => ['nullable', 'integer', 'min:0', 'max:255'],
  37. 'game_code' => ['nullable', 'string', 'max:128'],
  38. 'name' => ['nullable', 'string', 'max:128'],
  39. 'keyword' => ['nullable', 'string', 'max:128'],
  40. 'ingress' => ['nullable', Rule::in(EgameItem::ingressValues())],
  41. 'network' => ['nullable', Rule::in(EgameItem::networkValues())],
  42. 'status' => ['nullable', 'integer', Rule::in([
  43. EgameItem::STATUS_DISABLED,
  44. EgameItem::STATUS_ENABLED,
  45. ])],
  46. 'page' => ['nullable', 'integer', 'min:1'],
  47. 'limit' => ['nullable', 'integer', 'min:1', 'max:200'],
  48. ]);
  49. $query = EgameItem::query();
  50. foreach (['item_type', 'plat_type', 'game_type', 'game_code', 'status', 'ingress'] as $field) {
  51. $value = request()->input($field);
  52. if ($value !== null && $value !== '') {
  53. $query->where($field, $value);
  54. }
  55. }
  56. $network = trim((string) request()->input('network', ''));
  57. if ($network !== '') {
  58. $this->applyNetworkFilter($query, $network);
  59. }
  60. $name = trim((string) request()->input('name', ''));
  61. if ($name !== '') {
  62. $query->where('name', 'like', "%{$name}%");
  63. }
  64. $platformScope = (string) request()->input('platform_scope', '');
  65. if ($platformScope !== '') {
  66. $itemType = (string) request()->input('item_type', '');
  67. if ($itemType !== '' && $itemType !== EgameItem::TYPE_PLATFORM) {
  68. throw new Exception('platform_scope 只适用于平台配置', HttpStatus::CUSTOM_ERROR);
  69. }
  70. $query->where('item_type', EgameItem::TYPE_PLATFORM);
  71. if ($platformScope === EgameItem::PLATFORM_SCOPE_GLOBAL) {
  72. $query->where('game_type', 0);
  73. } else {
  74. $query->where('game_type', '>', 0);
  75. }
  76. }
  77. $keyword = trim((string) request()->input('keyword', ''));
  78. if ($keyword !== '') {
  79. $query->where(function ($query) use ($keyword) {
  80. $query->where('name', 'like', "%{$keyword}%")
  81. ->orWhere('plat_type', 'like', "%{$keyword}%")
  82. ->orWhere('game_code', 'like', "%{$keyword}%");
  83. });
  84. }
  85. $limit = (int) request()->input('limit', 15);
  86. $page = (int) request()->input('page', 1);
  87. $total = (clone $query)->count();
  88. $states = $this->catalogStates();
  89. $gameCountsByPlat = $this->gameCountsByPlat();
  90. $list = $query->orderByDesc('sort')
  91. ->orderByDesc('id')
  92. ->forPage($page, $limit)
  93. ->get()
  94. ->map(fn (EgameItem $item) => $this->decorateItem($item, $states, $gameCountsByPlat))
  95. ->values();
  96. } catch (ValidationException $e) {
  97. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  98. } catch (Exception $e) {
  99. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  100. }
  101. return $this->success(['total' => $total, 'data' => $list]);
  102. }
  103. public function options(): JsonResponse
  104. {
  105. try {
  106. $states = $this->catalogStates();
  107. $categoryPlatformCounts = $this->groupedCounts(
  108. EgameItem::query()
  109. ->where('item_type', EgameItem::TYPE_PLATFORM)
  110. ->where('game_type', '>', 0),
  111. 'game_type',
  112. 'plat_type'
  113. );
  114. $categoryGameCounts = $this->groupedCounts(
  115. EgameItem::query()->where('item_type', EgameItem::TYPE_GAME),
  116. 'game_type',
  117. 'id'
  118. );
  119. $platformCategoryCounts = $this->groupedCounts(
  120. EgameItem::query()
  121. ->where('item_type', EgameItem::TYPE_PLATFORM)
  122. ->where('game_type', '>', 0),
  123. 'plat_type',
  124. 'game_type'
  125. );
  126. $platformGameCounts = $this->gameCountsByPlat();
  127. $categories = EgameItem::query()
  128. ->where('item_type', EgameItem::TYPE_CATEGORY)
  129. ->orderByDesc('sort')
  130. ->orderBy('game_type')
  131. ->get()
  132. ->map(function (EgameItem $item) use ($states, $categoryPlatformCounts, $categoryGameCounts) {
  133. $this->decorateItem($item, $states);
  134. $key = (string) $item->game_type;
  135. $item->setAttribute('platform_count', $categoryPlatformCounts[$key] ?? 0);
  136. $item->setAttribute('game_count', $categoryGameCounts[$key] ?? 0);
  137. return $item;
  138. })
  139. ->values();
  140. $platforms = EgameItem::query()
  141. ->where('item_type', EgameItem::TYPE_PLATFORM)
  142. ->where('game_type', 0)
  143. ->orderByDesc('sort')
  144. ->orderBy('name')
  145. ->orderBy('plat_type')
  146. ->get()
  147. ->map(function (EgameItem $item) use ($states, $platformCategoryCounts, $platformGameCounts) {
  148. $this->decorateItem($item, $states, $platformGameCounts);
  149. $key = strtolower((string) $item->plat_type);
  150. $item->setAttribute('category_count', $platformCategoryCounts[$key] ?? 0);
  151. $item->setAttribute('game_count', $platformGameCounts[$key] ?? 0);
  152. return $item;
  153. })
  154. ->values();
  155. } catch (Exception $e) {
  156. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  157. }
  158. return $this->success([
  159. 'categories' => $categories,
  160. 'platforms' => $platforms,
  161. 'statuses' => EgameItem::optionList(EgameItem::STATUS_LABELS),
  162. 'ingress' => EgameItem::optionList(EgameItem::INGRESS_LABELS),
  163. 'networks' => array_merge(
  164. [['value' => '', 'label' => '不限制']],
  165. EgameItem::optionList(EgameItem::NETWORK_LABELS)
  166. ),
  167. ]);
  168. }
  169. public function update(): JsonResponse
  170. {
  171. try {
  172. request()->validate([
  173. 'id' => ['nullable', 'integer', 'min:0'],
  174. 'item_type' => ['nullable', Rule::in([
  175. EgameItem::TYPE_CATEGORY,
  176. EgameItem::TYPE_PLATFORM,
  177. EgameItem::TYPE_GAME,
  178. ])],
  179. 'platform_scope' => ['nullable', Rule::in([
  180. EgameItem::PLATFORM_SCOPE_GLOBAL,
  181. EgameItem::PLATFORM_SCOPE_CATEGORY,
  182. ])],
  183. 'plat_type' => ['nullable', 'string', 'max:32'],
  184. 'game_type' => ['nullable', 'integer', 'min:0', 'max:255'],
  185. 'game_code' => ['nullable', 'string', 'max:128'],
  186. 'name' => ['nullable', 'string', 'max:128'],
  187. 'description' => ['nullable', 'string', 'max:255'],
  188. 'ingress' => ['nullable', Rule::in(EgameItem::ingressValues())],
  189. 'network' => ['nullable', Rule::in(array_merge([''], EgameItem::networkValues()))],
  190. 'lobby_enabled' => ['nullable', 'boolean'],
  191. 'logo' => ['nullable', 'string', 'max:500'],
  192. 'logo_pc' => ['nullable', 'string', 'max:500'],
  193. 'logo_h5' => ['nullable', 'string', 'max:500'],
  194. 'icon' => ['nullable', 'string', 'max:500'],
  195. 'logo_langs' => ['nullable', 'array'],
  196. 'status' => ['nullable', 'integer', Rule::in([
  197. EgameItem::STATUS_DISABLED,
  198. EgameItem::STATUS_ENABLED,
  199. ])],
  200. 'sort' => ['nullable', 'integer', 'min:-999999', 'max:999999'],
  201. 'apply_to_games' => ['nullable', 'boolean'],
  202. ]);
  203. $id = (int) request()->input('id', 0);
  204. $item = DB::transaction(function () use ($id) {
  205. if ($id > 0) {
  206. $item = EgameItem::query()->find($id);
  207. if (!$item) {
  208. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  209. }
  210. $this->assertIdentityUnchanged($item);
  211. } else {
  212. $identity = $this->normalizedIdentityForCreate();
  213. $item = EgameItem::query()->firstOrNew($identity);
  214. }
  215. $data = $this->mutableItemData($item, !$item->exists);
  216. $name = array_key_exists('name', $data) ? $data['name'] : (string) $item->name;
  217. if ($item->isCategory() && trim($name) === '') {
  218. throw new Exception('分类名称不能为空', HttpStatus::CUSTOM_ERROR);
  219. }
  220. if (!empty($data) || !$item->exists) {
  221. $item->fill($data)->save();
  222. }
  223. $appliedGameCount = 0;
  224. if (array_key_exists('network', $data) && $item->isPlatformRelation()) {
  225. $appliedGameCount = $this->applyNetworkToGames(
  226. $item,
  227. (string) $data['network'],
  228. request()->boolean('apply_to_games', true)
  229. );
  230. }
  231. $item = $item->fresh();
  232. $item->setAttribute('applied_game_count', $appliedGameCount);
  233. return $item;
  234. });
  235. } catch (ValidationException $e) {
  236. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  237. } catch (Exception $e) {
  238. return $this->error((int) $e->getCode(), $e->getMessage());
  239. }
  240. return $this->success($this->decorateItem($item, $this->catalogStates(), $this->gameCountsByPlat()));
  241. }
  242. public function setStatus(): JsonResponse
  243. {
  244. try {
  245. request()->validate([
  246. 'id' => ['required', 'integer', 'min:1'],
  247. 'status' => ['required', 'integer', Rule::in([
  248. EgameItem::STATUS_DISABLED,
  249. EgameItem::STATUS_ENABLED,
  250. ])],
  251. ]);
  252. $item = EgameItem::query()->find((int) request()->input('id'));
  253. if (!$item) {
  254. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  255. }
  256. $item->status = (int) request()->input('status');
  257. $item->save();
  258. $item = $item->fresh();
  259. } catch (ValidationException $e) {
  260. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  261. } catch (Exception $e) {
  262. return $this->error((int) $e->getCode(), $e->getMessage());
  263. }
  264. return $this->success($this->decorateItem($item, $this->catalogStates(), $this->gameCountsByPlat()));
  265. }
  266. public function delete(): JsonResponse
  267. {
  268. try {
  269. request()->validate([
  270. 'id' => ['required', 'integer', 'min:1'],
  271. ]);
  272. if (!EgameItem::query()->whereKey((int) request()->input('id'))->exists()) {
  273. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  274. }
  275. } catch (ValidationException $e) {
  276. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  277. } catch (Exception $e) {
  278. return $this->error((int) $e->getCode(), $e->getMessage());
  279. }
  280. return $this->error(
  281. HttpStatus::CUSTOM_ERROR,
  282. '第三方游戏目录由同步任务维护,不能删除,请将状态设为关闭'
  283. );
  284. }
  285. private function normalizedIdentityForCreate(): array
  286. {
  287. $input = request()->all();
  288. if (!array_key_exists('item_type', $input) || !array_key_exists('game_type', $input)) {
  289. throw new Exception('新增配置必须填写 item_type 和 game_type', HttpStatus::CUSTOM_ERROR);
  290. }
  291. $itemType = (string) request()->input('item_type', '');
  292. $platformScope = (string) request()->input('platform_scope', '');
  293. if (!in_array($itemType, [
  294. EgameItem::TYPE_CATEGORY,
  295. EgameItem::TYPE_PLATFORM,
  296. EgameItem::TYPE_GAME,
  297. ], true)) {
  298. throw new Exception('item_type 参数错误', HttpStatus::CUSTOM_ERROR);
  299. }
  300. if ($platformScope !== '' && $itemType !== EgameItem::TYPE_PLATFORM) {
  301. throw new Exception('platform_scope 只适用于平台配置', HttpStatus::CUSTOM_ERROR);
  302. }
  303. $identity = [
  304. 'item_type' => $itemType,
  305. 'plat_type' => strtolower(trim((string) request()->input('plat_type', ''))),
  306. 'game_type' => (int) request()->input('game_type'),
  307. 'game_code' => trim((string) request()->input('game_code', '')),
  308. ];
  309. if ($itemType === EgameItem::TYPE_CATEGORY) {
  310. if ($identity['game_type'] <= 0) {
  311. throw new Exception('分类 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  312. }
  313. $identity['plat_type'] = '';
  314. $identity['game_code'] = '';
  315. return $identity;
  316. }
  317. if ($identity['plat_type'] === '') {
  318. throw new Exception('平台代码不能为空', HttpStatus::CUSTOM_ERROR);
  319. }
  320. if ($itemType === EgameItem::TYPE_PLATFORM) {
  321. if ($platformScope === EgameItem::PLATFORM_SCOPE_GLOBAL) {
  322. $identity['game_type'] = 0;
  323. }
  324. if ($platformScope === EgameItem::PLATFORM_SCOPE_CATEGORY && $identity['game_type'] <= 0) {
  325. throw new Exception('平台分类关联的 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  326. }
  327. $identity['game_code'] = '';
  328. return $identity;
  329. }
  330. if ($identity['game_type'] <= 0) {
  331. throw new Exception('游戏 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  332. }
  333. if ($identity['game_code'] === '') {
  334. throw new Exception('游戏配置必须填写 game_code', HttpStatus::CUSTOM_ERROR);
  335. }
  336. return $identity;
  337. }
  338. private function assertIdentityUnchanged(EgameItem $item): void
  339. {
  340. $input = request()->all();
  341. $checks = [
  342. 'item_type' => (string) $item->item_type,
  343. 'plat_type' => strtolower((string) $item->plat_type),
  344. 'game_type' => (int) $item->game_type,
  345. 'game_code' => (string) $item->game_code,
  346. ];
  347. foreach ($checks as $field => $expected) {
  348. if (!array_key_exists($field, $input) || $input[$field] === null) {
  349. continue;
  350. }
  351. $actual = $input[$field];
  352. if ($field === 'plat_type') {
  353. $actual = strtolower(trim((string) $actual));
  354. } elseif ($field === 'game_type') {
  355. $actual = (int) $actual;
  356. } else {
  357. $actual = trim((string) $actual);
  358. }
  359. if ($actual !== $expected) {
  360. throw new Exception('目录标识不允许修改:' . $field, HttpStatus::CUSTOM_ERROR);
  361. }
  362. }
  363. if (
  364. array_key_exists('platform_scope', $input)
  365. && $input['platform_scope'] !== null
  366. && $input['platform_scope'] !== ''
  367. ) {
  368. $expectedScope = '';
  369. if ($item->isGlobalPlatform()) {
  370. $expectedScope = EgameItem::PLATFORM_SCOPE_GLOBAL;
  371. } elseif ($item->isPlatformRelation()) {
  372. $expectedScope = EgameItem::PLATFORM_SCOPE_CATEGORY;
  373. }
  374. if ((string) $input['platform_scope'] !== $expectedScope) {
  375. throw new Exception('目录标识不允许修改:platform_scope', HttpStatus::CUSTOM_ERROR);
  376. }
  377. }
  378. }
  379. private function mutableItemData(EgameItem $item, bool $isNew): array
  380. {
  381. $input = request()->all();
  382. $data = $isNew ? [
  383. 'name' => '',
  384. 'description' => '',
  385. 'ingress' => EgameItem::INGRESS_BOTH,
  386. 'network' => '',
  387. 'lobby_enabled' => 0,
  388. 'logo' => '',
  389. 'logo_h5' => '',
  390. 'icon' => '',
  391. 'logo_langs' => null,
  392. 'status' => EgameItem::STATUS_ENABLED,
  393. 'sort' => 0,
  394. ] : [];
  395. foreach (['name', 'description', 'ingress', 'network'] as $field) {
  396. if (array_key_exists($field, $input)) {
  397. $data[$field] = trim((string) $input[$field]);
  398. }
  399. }
  400. if (array_key_exists('logo_h5', $input)) {
  401. $data['logo_h5'] = $this->logoPathForStorage((string) $input['logo_h5']);
  402. }
  403. if (array_key_exists('icon', $input)) {
  404. $data['icon'] = $item->item_type === EgameItem::TYPE_GAME
  405. ? ''
  406. : $this->logoPathForStorage((string) $input['icon']);
  407. }
  408. // logo_pc 是新版后台使用的 PC Logo 字段,数据库仍统一保存到 logo。
  409. // 两个字段同时出现时以 logo_pc 为准,避免列表整行回传的旧 logo
  410. // 覆盖用户刚上传的新 logo_pc;同时修复新增记录只传 logo_pc 无法保存。
  411. if (array_key_exists('logo', $input)) {
  412. $data['logo'] = $this->logoPathForStorage((string) $input['logo']);
  413. }
  414. if (array_key_exists('logo_pc', $input)) {
  415. $data['logo'] = $this->logoPathForStorage((string) $input['logo_pc']);
  416. }
  417. if (array_key_exists('logo_langs', $input)) {
  418. $data['logo_langs'] = $item->item_type === EgameItem::TYPE_GAME
  419. ? $this->logoLangsForStorage($input['logo_langs'])
  420. : null;
  421. }
  422. if (array_key_exists('status', $input)) {
  423. $data['status'] = (int) $input['status'];
  424. }
  425. if (array_key_exists('sort', $input)) {
  426. $data['sort'] = (int) $input['sort'];
  427. }
  428. if (array_key_exists('lobby_enabled', $input)) {
  429. $data['lobby_enabled'] = $item->isPlatformRelation()
  430. ? (int) request()->boolean('lobby_enabled')
  431. : 0;
  432. }
  433. if ($item->isCategory() && array_key_exists('ingress', $data)) {
  434. $data['ingress'] = EgameItem::INGRESS_BOTH;
  435. }
  436. if ($item->isCategory() && array_key_exists('network', $data)) {
  437. $data['network'] = '';
  438. }
  439. if ($item->item_type !== EgameItem::TYPE_GAME && array_key_exists('logo_langs', $data)) {
  440. $data['logo_langs'] = null;
  441. }
  442. if (!$item->isPlatformRelation() && array_key_exists('lobby_enabled', $data)) {
  443. $data['lobby_enabled'] = 0;
  444. }
  445. return $data;
  446. }
  447. private function catalogStates(): array
  448. {
  449. $states = [
  450. 'categories' => [],
  451. 'global_platforms' => [],
  452. 'platform_relations' => [],
  453. ];
  454. $rows = EgameItem::query()
  455. ->whereIn('item_type', [EgameItem::TYPE_CATEGORY, EgameItem::TYPE_PLATFORM])
  456. ->get();
  457. foreach ($rows as $row) {
  458. if ($row->isCategory()) {
  459. $states['categories'][(string) $row->game_type] = $row;
  460. continue;
  461. }
  462. $platType = strtolower((string) $row->plat_type);
  463. if ($row->isGlobalPlatform()) {
  464. $states['global_platforms'][$platType] = $row;
  465. continue;
  466. }
  467. if ($row->isPlatformRelation()) {
  468. $states['platform_relations'][$platType][(string) $row->game_type] = $row;
  469. }
  470. }
  471. return $states;
  472. }
  473. private function decorateItem(EgameItem $item, array $states, array $gameCountsByPlat = []): EgameItem
  474. {
  475. $platType = strtolower((string) $item->plat_type);
  476. $gameType = (string) $item->game_type;
  477. $disabledBy = null;
  478. $category = $states['categories'][$gameType] ?? null;
  479. $globalPlatform = $states['global_platforms'][$platType] ?? null;
  480. $platformRelation = $states['platform_relations'][$platType][$gameType] ?? null;
  481. if ($item->isCategory()) {
  482. if (!$this->enabled($item)) {
  483. $disabledBy = 'category';
  484. }
  485. } elseif ($item->isGlobalPlatform()) {
  486. if (!$this->enabled($item)) {
  487. $disabledBy = 'platform';
  488. }
  489. } elseif ($item->isPlatformRelation()) {
  490. if (!$this->enabled($category)) {
  491. $disabledBy = 'category';
  492. } elseif (!$this->enabled($globalPlatform)) {
  493. $disabledBy = 'platform';
  494. } elseif (!$this->enabled($item)) {
  495. $disabledBy = 'platform_category';
  496. }
  497. } else {
  498. if (!$this->enabled($category)) {
  499. $disabledBy = 'category';
  500. } elseif (!$this->enabled($globalPlatform)) {
  501. $disabledBy = 'platform';
  502. } elseif (!$this->enabled($platformRelation)) {
  503. $disabledBy = 'platform_category';
  504. } elseif (!$this->enabled($item)) {
  505. $disabledBy = 'game';
  506. }
  507. }
  508. $item->setAttribute('game_type_name', $this->gameTypeName((int) $item->game_type, $states));
  509. $item->setAttribute(
  510. 'platform_name',
  511. $this->platformName($item, $globalPlatform, $platformRelation)
  512. );
  513. if ($item->item_type === EgameItem::TYPE_PLATFORM) {
  514. $item->setAttribute(
  515. 'platform_scope',
  516. $item->isGlobalPlatform()
  517. ? EgameItem::PLATFORM_SCOPE_GLOBAL
  518. : EgameItem::PLATFORM_SCOPE_CATEGORY
  519. );
  520. } else {
  521. $item->setAttribute('platform_scope', null);
  522. }
  523. $item->setAttribute('effective_status', $disabledBy === null ? 1 : 0);
  524. $item->setAttribute('disabled_by', $disabledBy);
  525. $item->setAttribute('description', (string) ($item->description ?? ''));
  526. $logo = $this->absoluteLogoUrl((string) ($item->logo ?? ''));
  527. $item->setAttribute('logo', $logo);
  528. $item->setAttribute('logo_pc', $logo);
  529. $item->setAttribute('logo_h5', $this->absoluteLogoUrl((string) ($item->logo_h5 ?? '')));
  530. $item->setAttribute('icon', $this->absoluteLogoUrl((string) ($item->icon ?? '')));
  531. if (is_array($item->logo_langs)) {
  532. $item->setAttribute('logo_langs', array_map(
  533. fn ($path): string => $this->absoluteLogoUrl((string) $path),
  534. $item->logo_langs
  535. ));
  536. }
  537. $this->decorateNetwork($item, $globalPlatform, $platformRelation);
  538. $item->setAttribute('ingress_name', EgameItem::ingressName($item->ingress ?? ''));
  539. $item->setAttribute('status_name', EgameItem::STATUS_LABELS[(int) $item->status] ?? '');
  540. $gameCount = $gameCountsByPlat[$platType] ?? 0;
  541. $item->setAttribute(
  542. 'has_game_manage',
  543. $item->item_type === EgameItem::TYPE_PLATFORM && $gameCount > 0
  544. );
  545. if ($item->item_type === EgameItem::TYPE_PLATFORM) {
  546. $item->setAttribute('game_count', $gameCount);
  547. }
  548. return $item;
  549. }
  550. private function absoluteLogoUrl(string $path): string
  551. {
  552. $path = trim($path);
  553. if ($path === '' || preg_match('/^(?:https?:)?\/\//i', $path) || preg_match('/^(?:data|blob):/i', $path)) {
  554. return $path;
  555. }
  556. $relativePath = '/' . ltrim($path, '/');
  557. $baseUrl = $this->normalizedLogoBaseUrl((string) config('app.url', ''));
  558. if ($baseUrl === '') {
  559. $baseUrl = $this->normalizedLogoBaseUrl(request()->getSchemeAndHttpHost());
  560. }
  561. return $baseUrl . $relativePath;
  562. }
  563. private function logoPathForStorage(string $path): string
  564. {
  565. $path = trim($path);
  566. if ($path === '' || !preg_match('/^https?:\/\//i', $path)) {
  567. return $path;
  568. }
  569. $baseUrls = array_filter(array_unique([
  570. $this->normalizedLogoBaseUrl((string) config('app.url', '')),
  571. $this->normalizedLogoBaseUrl(request()->getSchemeAndHttpHost()),
  572. ]));
  573. foreach ($baseUrls as $baseUrl) {
  574. if (str_starts_with($path, $baseUrl . '/')) {
  575. return '/' . ltrim(substr($path, strlen($baseUrl)), '/');
  576. }
  577. }
  578. return $path;
  579. }
  580. private function normalizedLogoBaseUrl(string $baseUrl): string
  581. {
  582. $baseUrl = rtrim(trim($baseUrl), '/');
  583. if ($baseUrl !== '' && !preg_match('/^https?:\/\//i', $baseUrl)) {
  584. $baseUrl = 'https://' . $baseUrl;
  585. }
  586. return $baseUrl;
  587. }
  588. private function logoLangsForStorage($logos): array
  589. {
  590. if (!is_array($logos)) {
  591. return [];
  592. }
  593. return array_map(
  594. fn ($path): string => $this->logoPathForStorage((string) $path),
  595. $logos
  596. );
  597. }
  598. private function gameCountsByPlat(): array
  599. {
  600. $counts = [];
  601. foreach ($this->groupedCounts(
  602. EgameItem::query()->where('item_type', EgameItem::TYPE_GAME),
  603. 'plat_type',
  604. 'id'
  605. ) as $platType => $count) {
  606. $counts[strtolower((string) $platType)] = (int) $count;
  607. }
  608. return $counts;
  609. }
  610. private function decorateNetwork(
  611. EgameItem $item,
  612. ?EgameItem $globalPlatform,
  613. ?EgameItem $platformRelation
  614. ): void {
  615. $own = trim((string) ($item->network ?? ''));
  616. $inherited = '';
  617. if ($own === '') {
  618. if ($item->item_type === EgameItem::TYPE_GAME) {
  619. $parent = trim((string) ($platformRelation->network ?? ''));
  620. if ($parent === '') {
  621. $parent = trim((string) ($globalPlatform->network ?? ''));
  622. }
  623. $inherited = $parent;
  624. } elseif ($item->isPlatformRelation()) {
  625. $inherited = trim((string) ($globalPlatform->network ?? ''));
  626. }
  627. }
  628. $effective = $own !== '' ? $own : $inherited;
  629. $item->setAttribute('network', $own);
  630. $item->setAttribute('network_effective', $effective);
  631. $item->setAttribute('network_inherited', $own === '' && $effective !== '');
  632. $item->setAttribute('network_name', EgameItem::networkName($effective));
  633. }
  634. private function applyNetworkToGames(EgameItem $item, string $network, bool $apply): int
  635. {
  636. if (!$apply) {
  637. return 0;
  638. }
  639. return EgameItem::query()
  640. ->where('item_type', EgameItem::TYPE_GAME)
  641. ->where('plat_type', strtolower((string) $item->plat_type))
  642. ->where('game_type', (int) $item->game_type)
  643. ->update([
  644. 'network' => $network,
  645. 'updated_at' => now(),
  646. ]);
  647. }
  648. private function applyNetworkFilter($query, string $network): void
  649. {
  650. $itemType = (string) request()->input('item_type', '');
  651. $platType = strtolower(trim((string) request()->input('plat_type', '')));
  652. $gameType = request()->input('game_type');
  653. if ($itemType === EgameItem::TYPE_GAME && $platType !== '') {
  654. $parentNetwork = $this->parentNetwork($platType, $gameType);
  655. if ($parentNetwork === $network) {
  656. $query->where(function ($query) use ($network) {
  657. $query->where('network', $network)
  658. ->orWhere('network', '')
  659. ->orWhereNull('network');
  660. });
  661. return;
  662. }
  663. }
  664. $query->where('network', $network);
  665. }
  666. private function parentNetwork(string $platType, $gameType): string
  667. {
  668. if ($gameType !== null && $gameType !== '') {
  669. $relation = trim((string) EgameItem::query()
  670. ->where('item_type', EgameItem::TYPE_PLATFORM)
  671. ->where('plat_type', $platType)
  672. ->where('game_type', (int) $gameType)
  673. ->where('game_code', '')
  674. ->value('network'));
  675. if ($relation !== '') {
  676. return $relation;
  677. }
  678. }
  679. return trim((string) EgameItem::query()
  680. ->where('item_type', EgameItem::TYPE_PLATFORM)
  681. ->where('plat_type', $platType)
  682. ->where('game_type', 0)
  683. ->where('game_code', '')
  684. ->value('network'));
  685. }
  686. private function enabled(?EgameItem $item): bool
  687. {
  688. return $item !== null && $item->status === EgameItem::STATUS_ENABLED;
  689. }
  690. private function platformName(
  691. EgameItem $item,
  692. ?EgameItem $globalPlatform,
  693. ?EgameItem $platformRelation
  694. ): string {
  695. if ($item->isCategory()) {
  696. return '';
  697. }
  698. if ($item->isGlobalPlatform() && trim((string) $item->name) !== '') {
  699. return (string) $item->name;
  700. }
  701. if ($globalPlatform && trim((string) $globalPlatform->name) !== '') {
  702. return (string) $globalPlatform->name;
  703. }
  704. if ($platformRelation && trim((string) $platformRelation->name) !== '') {
  705. return (string) $platformRelation->name;
  706. }
  707. if ($item->item_type === EgameItem::TYPE_PLATFORM && trim((string) $item->name) !== '') {
  708. return (string) $item->name;
  709. }
  710. return (string) $item->plat_type;
  711. }
  712. private function gameTypeName(int $gameType, array $states): string
  713. {
  714. if ($gameType <= 0) {
  715. return '';
  716. }
  717. $category = $states['categories'][(string) $gameType] ?? null;
  718. if ($category && trim((string) $category->name) !== '') {
  719. return (string) $category->name;
  720. }
  721. return self::FALLBACK_GAME_TYPE_NAMES[$gameType] ?? ('分类' . $gameType);
  722. }
  723. private function groupedCounts($query, string $groupColumn, string $countColumn): array
  724. {
  725. return $query
  726. ->select($groupColumn)
  727. ->selectRaw("COUNT(DISTINCT {$countColumn}) AS aggregate")
  728. ->groupBy($groupColumn)
  729. ->pluck('aggregate', $groupColumn)
  730. ->map(fn ($count) => (int) $count)
  731. ->all();
  732. }
  733. }