NumericAttributesWhitelist.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. ];
  24. /**
  25. * 检查属性是否在白名单中
  26. *
  27. * @param string $attribute 属性名
  28. * @return bool 如果属性在白名单中返回true,否则返回false
  29. */
  30. public static function isAllowed(string $attribute): bool
  31. {
  32. return in_array($attribute, self::$whitelist);
  33. }
  34. /**
  35. * 过滤对象,只保留白名单中的属性
  36. *
  37. * @param object|array|null $attributes 要过滤的属性对象或数组
  38. * @return array|null 过滤后的属性数组,如果输入为null则返回null
  39. */
  40. public static function filter($attributes): ?array
  41. {
  42. if (is_null($attributes)) {
  43. return null;
  44. }
  45. // 如果是对象,转换为数组
  46. if (is_object($attributes)) {
  47. $attributes = (array)$attributes;
  48. }
  49. // 过滤数组,只保留白名单中的属性
  50. return array_filter(
  51. $attributes,
  52. function ($key) {
  53. return self::isAllowed($key);
  54. },
  55. ARRAY_FILTER_USE_KEY
  56. );
  57. }
  58. }