ChestContentWhitelist.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Module\GameItems\Config;
  3. /**
  4. * 宝箱内容属性白名单配置
  5. *
  6. * 用于定义在生成宝箱配置表时,宝箱内容中哪些属性应该被包含在输出中。
  7. * 未在白名单中的属性将被过滤掉,不会出现在生成的JSON配置中。
  8. */
  9. class ChestContentWhitelist
  10. {
  11. /**
  12. * 宝箱内容属性白名单
  13. *
  14. * 只有在此数组中列出的属性才会被包含在生成的宝箱配置表中
  15. *
  16. * @var array
  17. */
  18. public static array $whitelist = [
  19. 'item_id', // 物品ID
  20. 'type', // 类型(item或group)
  21. 'from_group', // 是否来自物品组
  22. ];
  23. /**
  24. * 检查属性是否在白名单中
  25. *
  26. * @param string $attribute 属性名
  27. * @return bool 如果属性在白名单中返回true,否则返回false
  28. */
  29. public static function isAllowed(string $attribute): bool
  30. {
  31. return in_array($attribute, self::$whitelist);
  32. }
  33. /**
  34. * 过滤对象,只保留白名单中的属性
  35. *
  36. * @param object|array|null $attributes 要过滤的属性对象或数组
  37. * @return array|null 过滤后的属性数组,如果输入为null则返回null
  38. */
  39. public static function filter($attributes): ?array
  40. {
  41. if (is_null($attributes)) {
  42. return null;
  43. }
  44. // 如果是对象,转换为数组
  45. if (is_object($attributes)) {
  46. $attributes = (array)$attributes;
  47. }
  48. // 过滤数组,只保留白名单中的属性
  49. return array_filter(
  50. $attributes,
  51. function ($key) {
  52. return self::isAllowed($key);
  53. },
  54. ARRAY_FILTER_USE_KEY
  55. );
  56. }
  57. }