UpdateRiseForm.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. <?php
  2. namespace hd\models\goods;
  3. use hd\models\BaseForm;
  4. /**
  5. * 商品涨价设置表单模型
  6. */
  7. class UpdateRiseForm extends BaseForm
  8. {
  9. /**
  10. * 节日ID列表
  11. * @var array
  12. */
  13. public $festIdList;
  14. /**
  15. * 涨价开关
  16. * @var int
  17. */
  18. public $riseSwitch;
  19. /**
  20. * 涨价类型 (0=百分比, 1=金额)
  21. * @var int
  22. */
  23. public $riseType;
  24. /**
  25. * 涨价金额或百分比
  26. * @var float
  27. */
  28. public $riseAmount;
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function rules()
  33. {
  34. return [
  35. // 默认值设置
  36. ['festIdList', 'default', 'value' => []],
  37. ['riseSwitch', 'default', 'value' => 1],
  38. // 数据类型验证
  39. // ['festIdList', 'validateFestIdList'],
  40. ['riseSwitch', 'in', 'range' => [0, 1]],
  41. ['riseType', 'in', 'range' => [0, 1]],
  42. ['riseAmount', 'validateRiseAmount'],
  43. ];
  44. }
  45. /**
  46. * 校验涨价金额或比例,允许 0,但不允许空值、非数字和负数。
  47. * @param string $attribute 属性名
  48. * @param array $params 参数
  49. */
  50. public function validateRiseAmount($attribute, $params)
  51. {
  52. $value = $this->$attribute;
  53. if ($this->riseSwitch != 1 && ($value === null || $value === '')) {
  54. return;
  55. }
  56. if ($value === null || $value === '') {
  57. $this->addError($attribute, '请设置涨价金额');
  58. return;
  59. }
  60. if (!is_scalar($value)) {
  61. $this->addError($attribute, '涨价金额/百分比必须为数字');
  62. return;
  63. }
  64. $value = trim((string)$value);
  65. if ($value === '') {
  66. $this->addError($attribute, '请设置涨价金额');
  67. return;
  68. }
  69. if (!is_numeric($value)) {
  70. $this->addError($attribute, '涨价金额/百分比必须为数字');
  71. return;
  72. }
  73. if ($value < 0) {
  74. $this->addError($attribute, '涨价金额/百分比不能小于0');
  75. }
  76. }
  77. /**
  78. * 验证节日ID列表
  79. * @param string $attribute 属性名
  80. * @param array $params 参数
  81. */
  82. public function validateFestIdList($attribute, $params)
  83. {
  84. if (!empty($this->$attribute)) {
  85. if (!is_array($this->$attribute)) {
  86. $this->addError($attribute, '节日列表格式不正确');
  87. return;
  88. }
  89. foreach ($this->$attribute as $festId) {
  90. if (!is_numeric($festId) || $festId <= 0) {
  91. $this->addError($attribute, '节日ID必须为正整数');
  92. return;
  93. }
  94. }
  95. }
  96. }
  97. /**
  98. * 获取属性标签
  99. * @return array
  100. */
  101. public function attributeLabels()
  102. {
  103. return [
  104. 'festIdList' => '节日列表',
  105. 'riseSwitch' => '涨价开关',
  106. 'riseType' => '涨价类型',
  107. 'riseAmount' => '涨价金额/百分比',
  108. ];
  109. }
  110. }