ChestCostWhitelist.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Module\GameItems\Config;
  3. /**
  4. * 宝箱开启消耗属性白名单配置
  5. *
  6. * 用于定义在生成宝箱配置表时,宝箱开启消耗中哪些属性应该被包含在输出中。
  7. * 未在白名单中的属性将被过滤掉,不会出现在生成的JSON配置中。
  8. */
  9. class ChestCostWhitelist
  10. {
  11. /**
  12. * 宝箱开启消耗属性白名单
  13. *
  14. * 只有在此数组中列出的属性才会被包含在生成的宝箱配置表中
  15. *
  16. * @var array
  17. */
  18. public static array $whitelist = [
  19. 'cost_type', // 消耗类型
  20. 'cost_id', // 消耗ID
  21. 'cost_quantity', // 消耗数量
  22. 'item_name', // 物品名称(当cost_type为物品时)
  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. }