DisasterResistanceCast.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Module\Farm\Casts;
  3. use App\Module\Farm\Enums\DISASTER_TYPE;
  4. use UCore\Model\CastsAttributes;
  5. /**
  6. * 灾害抵抗属性类型转换器
  7. *
  8. * 用于将数据库中存储的JSON格式的灾害抵抗属性转换为PHP对象,以及将PHP对象转换回JSON格式。
  9. * 灾害抵抗属性包含对不同类型灾害的抵抗率,如干旱、虫害、杂草等。
  10. */
  11. class DisasterResistanceCast extends CastsAttributes
  12. {
  13. /**
  14. * 干旱抵抗率(百分比格式,1=1%,100=100%)
  15. *
  16. * @var float $drought
  17. */
  18. public float $drought = 0.0;
  19. /**
  20. * 虫害抵抗率(百分比格式,1=1%,100=100%)
  21. *
  22. * @var float $pest
  23. */
  24. public float $pest = 0.0;
  25. /**
  26. * 杂草抵抗率(百分比格式,1=1%,100=100%)
  27. *
  28. * @var float $weed
  29. */
  30. public float $weed = 0.0;
  31. /**
  32. * 获取指定灾害类型的抵抗率
  33. *
  34. * @param DISASTER_TYPE|int $type 灾害类型
  35. * @return float 抵抗率(百分比格式,1=1%,需要除以100转换为小数)
  36. */
  37. public function getResistance($type): float
  38. {
  39. if ($type instanceof DISASTER_TYPE) {
  40. $type = $type->value;
  41. }
  42. return match ($type) {
  43. DISASTER_TYPE::DROUGHT->value => $this->drought,
  44. DISASTER_TYPE::PEST->value => $this->pest,
  45. DISASTER_TYPE::WEED->value => $this->weed,
  46. default => 0.0,
  47. };
  48. }
  49. /**
  50. * 设置指定灾害类型的抵抗率
  51. *
  52. * @param DISASTER_TYPE|int $type 灾害类型
  53. * @param float $value 抵抗率
  54. * @return self
  55. */
  56. public function setResistance($type, float $value): self
  57. {
  58. if ($type instanceof DISASTER_TYPE) {
  59. $type = $type->value;
  60. }
  61. match ($type) {
  62. DISASTER_TYPE::DROUGHT->value => $this->drought = $value,
  63. DISASTER_TYPE::PEST->value => $this->pest = $value,
  64. DISASTER_TYPE::WEED->value => $this->weed = $value,
  65. default => null,
  66. };
  67. return $this;
  68. }
  69. }