NumericAttributesWhitelist.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace App\Module\GameItems\Config;
  3. /**
  4. * 物品数值属性白名单配置
  5. *
  6. * 用于定义在生成物品配置表时,哪些数值属性应该被包含在输出中。
  7. * 未在白名单中的属性将被过滤掉,不会出现在生成的JSON配置中。
  8. */
  9. class NumericAttributesWhitelist
  10. {
  11. /**
  12. * 物品数值属性白名单
  13. *
  14. * 只有在此数组中列出的属性才会被包含在生成的物品配置表中
  15. *
  16. * @var array
  17. */
  18. public static array $whitelist = [
  19. 'crop_growth_time', // 减少作物生长时间
  20. 'pet_power', // 增加宠物体力
  21. 'pet_exp', // 增加宠物经验
  22. 'reward_group_id', // 使用后随机奖励物品组
  23. 'fram_remove_reward_group',// 铲除奖励组
  24. ];
  25. /**
  26. * 检查属性是否在白名单中
  27. *
  28. * @param string $attribute 属性名
  29. * @return bool 如果属性在白名单中返回true,否则返回false
  30. */
  31. public static function isAllowed(string $attribute): bool
  32. {
  33. return in_array($attribute, self::$whitelist);
  34. }
  35. /**
  36. * 过滤对象,只保留白名单中的属性
  37. *
  38. * @param object|array|null $attributes 要过滤的属性对象或数组
  39. * @return array|null 过滤后的属性数组,如果输入为null则返回null
  40. */
  41. public static function filter($attributes): ?array
  42. {
  43. if (is_null($attributes)) {
  44. return null;
  45. }
  46. // 如果是对象,转换为数组
  47. if (is_object($attributes)) {
  48. $attributes = (array)$attributes;
  49. }
  50. // 过滤数组,只保留白名单中的属性
  51. return array_filter(
  52. $attributes,
  53. function ($key) {
  54. return self::isAllowed($key);
  55. },
  56. ARRAY_FILTER_USE_KEY
  57. );
  58. }
  59. }