Egame.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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. 'logo_langs' => ['nullable', 'array'],
  195. 'status' => ['nullable', 'integer', Rule::in([
  196. EgameItem::STATUS_DISABLED,
  197. EgameItem::STATUS_ENABLED,
  198. ])],
  199. 'sort' => ['nullable', 'integer', 'min:-999999', 'max:999999'],
  200. 'apply_to_games' => ['nullable', 'boolean'],
  201. ]);
  202. $id = (int) request()->input('id', 0);
  203. $item = DB::transaction(function () use ($id) {
  204. if ($id > 0) {
  205. $item = EgameItem::query()->find($id);
  206. if (!$item) {
  207. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  208. }
  209. $this->assertIdentityUnchanged($item);
  210. } else {
  211. $identity = $this->normalizedIdentityForCreate();
  212. $item = EgameItem::query()->firstOrNew($identity);
  213. }
  214. $data = $this->mutableItemData($item, !$item->exists);
  215. $name = array_key_exists('name', $data) ? $data['name'] : (string) $item->name;
  216. if ($item->isCategory() && trim($name) === '') {
  217. throw new Exception('分类名称不能为空', HttpStatus::CUSTOM_ERROR);
  218. }
  219. if (!empty($data) || !$item->exists) {
  220. $item->fill($data)->save();
  221. }
  222. $appliedGameCount = 0;
  223. if (array_key_exists('network', $data) && $item->isPlatformRelation()) {
  224. $appliedGameCount = $this->applyNetworkToGames(
  225. $item,
  226. (string) $data['network'],
  227. request()->boolean('apply_to_games', true)
  228. );
  229. }
  230. $item = $item->fresh();
  231. $item->setAttribute('applied_game_count', $appliedGameCount);
  232. return $item;
  233. });
  234. } catch (ValidationException $e) {
  235. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  236. } catch (Exception $e) {
  237. return $this->error((int) $e->getCode(), $e->getMessage());
  238. }
  239. return $this->success($this->decorateItem($item, $this->catalogStates(), $this->gameCountsByPlat()));
  240. }
  241. public function setStatus(): JsonResponse
  242. {
  243. try {
  244. request()->validate([
  245. 'id' => ['required', 'integer', 'min:1'],
  246. 'status' => ['required', 'integer', Rule::in([
  247. EgameItem::STATUS_DISABLED,
  248. EgameItem::STATUS_ENABLED,
  249. ])],
  250. ]);
  251. $item = EgameItem::query()->find((int) request()->input('id'));
  252. if (!$item) {
  253. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  254. }
  255. $item->status = (int) request()->input('status');
  256. $item->save();
  257. $item = $item->fresh();
  258. } catch (ValidationException $e) {
  259. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  260. } catch (Exception $e) {
  261. return $this->error((int) $e->getCode(), $e->getMessage());
  262. }
  263. return $this->success($this->decorateItem($item, $this->catalogStates(), $this->gameCountsByPlat()));
  264. }
  265. public function delete(): JsonResponse
  266. {
  267. try {
  268. request()->validate([
  269. 'id' => ['required', 'integer', 'min:1'],
  270. ]);
  271. if (!EgameItem::query()->whereKey((int) request()->input('id'))->exists()) {
  272. throw new Exception('配置不存在', HttpStatus::CUSTOM_ERROR);
  273. }
  274. } catch (ValidationException $e) {
  275. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  276. } catch (Exception $e) {
  277. return $this->error((int) $e->getCode(), $e->getMessage());
  278. }
  279. return $this->error(
  280. HttpStatus::CUSTOM_ERROR,
  281. '第三方游戏目录由同步任务维护,不能删除,请将状态设为关闭'
  282. );
  283. }
  284. private function normalizedIdentityForCreate(): array
  285. {
  286. $input = request()->all();
  287. if (!array_key_exists('item_type', $input) || !array_key_exists('game_type', $input)) {
  288. throw new Exception('新增配置必须填写 item_type 和 game_type', HttpStatus::CUSTOM_ERROR);
  289. }
  290. $itemType = (string) request()->input('item_type', '');
  291. $platformScope = (string) request()->input('platform_scope', '');
  292. if (!in_array($itemType, [
  293. EgameItem::TYPE_CATEGORY,
  294. EgameItem::TYPE_PLATFORM,
  295. EgameItem::TYPE_GAME,
  296. ], true)) {
  297. throw new Exception('item_type 参数错误', HttpStatus::CUSTOM_ERROR);
  298. }
  299. if ($platformScope !== '' && $itemType !== EgameItem::TYPE_PLATFORM) {
  300. throw new Exception('platform_scope 只适用于平台配置', HttpStatus::CUSTOM_ERROR);
  301. }
  302. $identity = [
  303. 'item_type' => $itemType,
  304. 'plat_type' => strtolower(trim((string) request()->input('plat_type', ''))),
  305. 'game_type' => (int) request()->input('game_type'),
  306. 'game_code' => trim((string) request()->input('game_code', '')),
  307. ];
  308. if ($itemType === EgameItem::TYPE_CATEGORY) {
  309. if ($identity['game_type'] <= 0) {
  310. throw new Exception('分类 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  311. }
  312. $identity['plat_type'] = '';
  313. $identity['game_code'] = '';
  314. return $identity;
  315. }
  316. if ($identity['plat_type'] === '') {
  317. throw new Exception('平台代码不能为空', HttpStatus::CUSTOM_ERROR);
  318. }
  319. if ($itemType === EgameItem::TYPE_PLATFORM) {
  320. if ($platformScope === EgameItem::PLATFORM_SCOPE_GLOBAL) {
  321. $identity['game_type'] = 0;
  322. }
  323. if ($platformScope === EgameItem::PLATFORM_SCOPE_CATEGORY && $identity['game_type'] <= 0) {
  324. throw new Exception('平台分类关联的 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  325. }
  326. $identity['game_code'] = '';
  327. return $identity;
  328. }
  329. if ($identity['game_type'] <= 0) {
  330. throw new Exception('游戏 game_type 必须大于 0', HttpStatus::CUSTOM_ERROR);
  331. }
  332. if ($identity['game_code'] === '') {
  333. throw new Exception('游戏配置必须填写 game_code', HttpStatus::CUSTOM_ERROR);
  334. }
  335. return $identity;
  336. }
  337. private function assertIdentityUnchanged(EgameItem $item): void
  338. {
  339. $input = request()->all();
  340. $checks = [
  341. 'item_type' => (string) $item->item_type,
  342. 'plat_type' => strtolower((string) $item->plat_type),
  343. 'game_type' => (int) $item->game_type,
  344. 'game_code' => (string) $item->game_code,
  345. ];
  346. foreach ($checks as $field => $expected) {
  347. if (!array_key_exists($field, $input) || $input[$field] === null) {
  348. continue;
  349. }
  350. $actual = $input[$field];
  351. if ($field === 'plat_type') {
  352. $actual = strtolower(trim((string) $actual));
  353. } elseif ($field === 'game_type') {
  354. $actual = (int) $actual;
  355. } else {
  356. $actual = trim((string) $actual);
  357. }
  358. if ($actual !== $expected) {
  359. throw new Exception('目录标识不允许修改:' . $field, HttpStatus::CUSTOM_ERROR);
  360. }
  361. }
  362. if (
  363. array_key_exists('platform_scope', $input)
  364. && $input['platform_scope'] !== null
  365. && $input['platform_scope'] !== ''
  366. ) {
  367. $expectedScope = '';
  368. if ($item->isGlobalPlatform()) {
  369. $expectedScope = EgameItem::PLATFORM_SCOPE_GLOBAL;
  370. } elseif ($item->isPlatformRelation()) {
  371. $expectedScope = EgameItem::PLATFORM_SCOPE_CATEGORY;
  372. }
  373. if ((string) $input['platform_scope'] !== $expectedScope) {
  374. throw new Exception('目录标识不允许修改:platform_scope', HttpStatus::CUSTOM_ERROR);
  375. }
  376. }
  377. }
  378. private function mutableItemData(EgameItem $item, bool $isNew): array
  379. {
  380. $input = request()->all();
  381. $data = $isNew ? [
  382. 'name' => '',
  383. 'description' => '',
  384. 'ingress' => EgameItem::INGRESS_BOTH,
  385. 'network' => '',
  386. 'lobby_enabled' => 0,
  387. 'logo' => '',
  388. 'logo_h5' => '',
  389. 'logo_langs' => null,
  390. 'status' => EgameItem::STATUS_ENABLED,
  391. 'sort' => 0,
  392. ] : [];
  393. foreach (['name', 'description', 'ingress', 'network'] as $field) {
  394. if (array_key_exists($field, $input)) {
  395. $data[$field] = trim((string) $input[$field]);
  396. }
  397. }
  398. if (array_key_exists('logo_h5', $input)) {
  399. $data['logo_h5'] = $this->logoPathForStorage((string) $input['logo_h5']);
  400. }
  401. // logo_pc 是新版后台使用的 PC Logo 字段,数据库仍统一保存到 logo。
  402. // 两个字段同时出现时以 logo_pc 为准,避免列表整行回传的旧 logo
  403. // 覆盖用户刚上传的新 logo_pc;同时修复新增记录只传 logo_pc 无法保存。
  404. if (array_key_exists('logo', $input)) {
  405. $data['logo'] = $this->logoPathForStorage((string) $input['logo']);
  406. }
  407. if (array_key_exists('logo_pc', $input)) {
  408. $data['logo'] = $this->logoPathForStorage((string) $input['logo_pc']);
  409. }
  410. if (array_key_exists('logo_langs', $input)) {
  411. $data['logo_langs'] = $item->item_type === EgameItem::TYPE_GAME
  412. ? $this->logoLangsForStorage($input['logo_langs'])
  413. : null;
  414. }
  415. if (array_key_exists('status', $input)) {
  416. $data['status'] = (int) $input['status'];
  417. }
  418. if (array_key_exists('sort', $input)) {
  419. $data['sort'] = (int) $input['sort'];
  420. }
  421. if (array_key_exists('lobby_enabled', $input)) {
  422. $data['lobby_enabled'] = $item->isPlatformRelation()
  423. ? (int) request()->boolean('lobby_enabled')
  424. : 0;
  425. }
  426. if ($item->isCategory() && array_key_exists('ingress', $data)) {
  427. $data['ingress'] = EgameItem::INGRESS_BOTH;
  428. }
  429. if ($item->isCategory() && array_key_exists('network', $data)) {
  430. $data['network'] = '';
  431. }
  432. if ($item->item_type !== EgameItem::TYPE_GAME && array_key_exists('logo_langs', $data)) {
  433. $data['logo_langs'] = null;
  434. }
  435. if (!$item->isPlatformRelation() && array_key_exists('lobby_enabled', $data)) {
  436. $data['lobby_enabled'] = 0;
  437. }
  438. return $data;
  439. }
  440. private function catalogStates(): array
  441. {
  442. $states = [
  443. 'categories' => [],
  444. 'global_platforms' => [],
  445. 'platform_relations' => [],
  446. ];
  447. $rows = EgameItem::query()
  448. ->whereIn('item_type', [EgameItem::TYPE_CATEGORY, EgameItem::TYPE_PLATFORM])
  449. ->get();
  450. foreach ($rows as $row) {
  451. if ($row->isCategory()) {
  452. $states['categories'][(string) $row->game_type] = $row;
  453. continue;
  454. }
  455. $platType = strtolower((string) $row->plat_type);
  456. if ($row->isGlobalPlatform()) {
  457. $states['global_platforms'][$platType] = $row;
  458. continue;
  459. }
  460. if ($row->isPlatformRelation()) {
  461. $states['platform_relations'][$platType][(string) $row->game_type] = $row;
  462. }
  463. }
  464. return $states;
  465. }
  466. private function decorateItem(EgameItem $item, array $states, array $gameCountsByPlat = []): EgameItem
  467. {
  468. $platType = strtolower((string) $item->plat_type);
  469. $gameType = (string) $item->game_type;
  470. $disabledBy = null;
  471. $category = $states['categories'][$gameType] ?? null;
  472. $globalPlatform = $states['global_platforms'][$platType] ?? null;
  473. $platformRelation = $states['platform_relations'][$platType][$gameType] ?? null;
  474. if ($item->isCategory()) {
  475. if (!$this->enabled($item)) {
  476. $disabledBy = 'category';
  477. }
  478. } elseif ($item->isGlobalPlatform()) {
  479. if (!$this->enabled($item)) {
  480. $disabledBy = 'platform';
  481. }
  482. } elseif ($item->isPlatformRelation()) {
  483. if (!$this->enabled($category)) {
  484. $disabledBy = 'category';
  485. } elseif (!$this->enabled($globalPlatform)) {
  486. $disabledBy = 'platform';
  487. } elseif (!$this->enabled($item)) {
  488. $disabledBy = 'platform_category';
  489. }
  490. } else {
  491. if (!$this->enabled($category)) {
  492. $disabledBy = 'category';
  493. } elseif (!$this->enabled($globalPlatform)) {
  494. $disabledBy = 'platform';
  495. } elseif (!$this->enabled($platformRelation)) {
  496. $disabledBy = 'platform_category';
  497. } elseif (!$this->enabled($item)) {
  498. $disabledBy = 'game';
  499. }
  500. }
  501. $item->setAttribute('game_type_name', $this->gameTypeName((int) $item->game_type, $states));
  502. $item->setAttribute(
  503. 'platform_name',
  504. $this->platformName($item, $globalPlatform, $platformRelation)
  505. );
  506. if ($item->item_type === EgameItem::TYPE_PLATFORM) {
  507. $item->setAttribute(
  508. 'platform_scope',
  509. $item->isGlobalPlatform()
  510. ? EgameItem::PLATFORM_SCOPE_GLOBAL
  511. : EgameItem::PLATFORM_SCOPE_CATEGORY
  512. );
  513. } else {
  514. $item->setAttribute('platform_scope', null);
  515. }
  516. $item->setAttribute('effective_status', $disabledBy === null ? 1 : 0);
  517. $item->setAttribute('disabled_by', $disabledBy);
  518. $item->setAttribute('description', (string) ($item->description ?? ''));
  519. $logo = $this->absoluteLogoUrl((string) ($item->logo ?? ''));
  520. $item->setAttribute('logo', $logo);
  521. $item->setAttribute('logo_pc', $logo);
  522. $item->setAttribute('logo_h5', $this->absoluteLogoUrl((string) ($item->logo_h5 ?? '')));
  523. if (is_array($item->logo_langs)) {
  524. $item->setAttribute('logo_langs', array_map(
  525. fn ($path): string => $this->absoluteLogoUrl((string) $path),
  526. $item->logo_langs
  527. ));
  528. }
  529. $this->decorateNetwork($item, $globalPlatform, $platformRelation);
  530. $item->setAttribute('ingress_name', EgameItem::ingressName($item->ingress ?? ''));
  531. $item->setAttribute('status_name', EgameItem::STATUS_LABELS[(int) $item->status] ?? '');
  532. $gameCount = $gameCountsByPlat[$platType] ?? 0;
  533. $item->setAttribute(
  534. 'has_game_manage',
  535. $item->item_type === EgameItem::TYPE_PLATFORM && $gameCount > 0
  536. );
  537. if ($item->item_type === EgameItem::TYPE_PLATFORM) {
  538. $item->setAttribute('game_count', $gameCount);
  539. }
  540. return $item;
  541. }
  542. private function absoluteLogoUrl(string $path): string
  543. {
  544. $path = trim($path);
  545. if ($path === '' || preg_match('/^(?:https?:)?\/\//i', $path) || preg_match('/^(?:data|blob):/i', $path)) {
  546. return $path;
  547. }
  548. $relativePath = '/' . ltrim($path, '/');
  549. $baseUrl = $this->normalizedLogoBaseUrl((string) config('app.url', ''));
  550. if ($baseUrl === '') {
  551. $baseUrl = $this->normalizedLogoBaseUrl(request()->getSchemeAndHttpHost());
  552. }
  553. return $baseUrl . $relativePath;
  554. }
  555. private function logoPathForStorage(string $path): string
  556. {
  557. $path = trim($path);
  558. if ($path === '' || !preg_match('/^https?:\/\//i', $path)) {
  559. return $path;
  560. }
  561. $baseUrls = array_filter(array_unique([
  562. $this->normalizedLogoBaseUrl((string) config('app.url', '')),
  563. $this->normalizedLogoBaseUrl(request()->getSchemeAndHttpHost()),
  564. ]));
  565. foreach ($baseUrls as $baseUrl) {
  566. if (str_starts_with($path, $baseUrl . '/')) {
  567. return '/' . ltrim(substr($path, strlen($baseUrl)), '/');
  568. }
  569. }
  570. return $path;
  571. }
  572. private function normalizedLogoBaseUrl(string $baseUrl): string
  573. {
  574. $baseUrl = rtrim(trim($baseUrl), '/');
  575. if ($baseUrl !== '' && !preg_match('/^https?:\/\//i', $baseUrl)) {
  576. $baseUrl = 'https://' . $baseUrl;
  577. }
  578. return $baseUrl;
  579. }
  580. private function logoLangsForStorage($logos): array
  581. {
  582. if (!is_array($logos)) {
  583. return [];
  584. }
  585. return array_map(
  586. fn ($path): string => $this->logoPathForStorage((string) $path),
  587. $logos
  588. );
  589. }
  590. private function gameCountsByPlat(): array
  591. {
  592. $counts = [];
  593. foreach ($this->groupedCounts(
  594. EgameItem::query()->where('item_type', EgameItem::TYPE_GAME),
  595. 'plat_type',
  596. 'id'
  597. ) as $platType => $count) {
  598. $counts[strtolower((string) $platType)] = (int) $count;
  599. }
  600. return $counts;
  601. }
  602. private function decorateNetwork(
  603. EgameItem $item,
  604. ?EgameItem $globalPlatform,
  605. ?EgameItem $platformRelation
  606. ): void {
  607. $own = trim((string) ($item->network ?? ''));
  608. $inherited = '';
  609. if ($own === '') {
  610. if ($item->item_type === EgameItem::TYPE_GAME) {
  611. $parent = trim((string) ($platformRelation->network ?? ''));
  612. if ($parent === '') {
  613. $parent = trim((string) ($globalPlatform->network ?? ''));
  614. }
  615. $inherited = $parent;
  616. } elseif ($item->isPlatformRelation()) {
  617. $inherited = trim((string) ($globalPlatform->network ?? ''));
  618. }
  619. }
  620. $effective = $own !== '' ? $own : $inherited;
  621. $item->setAttribute('network', $own);
  622. $item->setAttribute('network_effective', $effective);
  623. $item->setAttribute('network_inherited', $own === '' && $effective !== '');
  624. $item->setAttribute('network_name', EgameItem::networkName($effective));
  625. }
  626. private function applyNetworkToGames(EgameItem $item, string $network, bool $apply): int
  627. {
  628. if (!$apply) {
  629. return 0;
  630. }
  631. return EgameItem::query()
  632. ->where('item_type', EgameItem::TYPE_GAME)
  633. ->where('plat_type', strtolower((string) $item->plat_type))
  634. ->where('game_type', (int) $item->game_type)
  635. ->update([
  636. 'network' => $network,
  637. 'updated_at' => now(),
  638. ]);
  639. }
  640. private function applyNetworkFilter($query, string $network): void
  641. {
  642. $itemType = (string) request()->input('item_type', '');
  643. $platType = strtolower(trim((string) request()->input('plat_type', '')));
  644. $gameType = request()->input('game_type');
  645. if ($itemType === EgameItem::TYPE_GAME && $platType !== '') {
  646. $parentNetwork = $this->parentNetwork($platType, $gameType);
  647. if ($parentNetwork === $network) {
  648. $query->where(function ($query) use ($network) {
  649. $query->where('network', $network)
  650. ->orWhere('network', '')
  651. ->orWhereNull('network');
  652. });
  653. return;
  654. }
  655. }
  656. $query->where('network', $network);
  657. }
  658. private function parentNetwork(string $platType, $gameType): string
  659. {
  660. if ($gameType !== null && $gameType !== '') {
  661. $relation = trim((string) EgameItem::query()
  662. ->where('item_type', EgameItem::TYPE_PLATFORM)
  663. ->where('plat_type', $platType)
  664. ->where('game_type', (int) $gameType)
  665. ->where('game_code', '')
  666. ->value('network'));
  667. if ($relation !== '') {
  668. return $relation;
  669. }
  670. }
  671. return trim((string) EgameItem::query()
  672. ->where('item_type', EgameItem::TYPE_PLATFORM)
  673. ->where('plat_type', $platType)
  674. ->where('game_type', 0)
  675. ->where('game_code', '')
  676. ->value('network'));
  677. }
  678. private function enabled(?EgameItem $item): bool
  679. {
  680. return $item !== null && $item->status === EgameItem::STATUS_ENABLED;
  681. }
  682. private function platformName(
  683. EgameItem $item,
  684. ?EgameItem $globalPlatform,
  685. ?EgameItem $platformRelation
  686. ): string {
  687. if ($item->isCategory()) {
  688. return '';
  689. }
  690. if ($item->isGlobalPlatform() && trim((string) $item->name) !== '') {
  691. return (string) $item->name;
  692. }
  693. if ($globalPlatform && trim((string) $globalPlatform->name) !== '') {
  694. return (string) $globalPlatform->name;
  695. }
  696. if ($platformRelation && trim((string) $platformRelation->name) !== '') {
  697. return (string) $platformRelation->name;
  698. }
  699. if ($item->item_type === EgameItem::TYPE_PLATFORM && trim((string) $item->name) !== '') {
  700. return (string) $item->name;
  701. }
  702. return (string) $item->plat_type;
  703. }
  704. private function gameTypeName(int $gameType, array $states): string
  705. {
  706. if ($gameType <= 0) {
  707. return '';
  708. }
  709. $category = $states['categories'][(string) $gameType] ?? null;
  710. if ($category && trim((string) $category->name) !== '') {
  711. return (string) $category->name;
  712. }
  713. return self::FALLBACK_GAME_TYPE_NAMES[$gameType] ?? ('分类' . $gameType);
  714. }
  715. private function groupedCounts($query, string $groupColumn, string $countColumn): array
  716. {
  717. return $query
  718. ->select($groupColumn)
  719. ->selectRaw("COUNT(DISTINCT {$countColumn}) AS aggregate")
  720. ->groupBy($groupColumn)
  721. ->pluck('aggregate', $groupColumn)
  722. ->map(fn ($count) => (int) $count)
  723. ->all();
  724. }
  725. }