PersonalPasswdForm.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace backend\forms;
  3. use Yii;
  4. use yii\base\Model;
  5. use common\models\member\Member;
  6. /**
  7. * 修改密码表单
  8. *
  9. * Class PasswdForm
  10. * @package backend\modules\base\models
  11. * @author jianyan74 <751393839@qq.com>
  12. */
  13. class PersonalPasswdForm extends Model
  14. {
  15. public $passwd;
  16. public $passwd_new;
  17. public $passwd_repetition;
  18. /**
  19. * @var Member
  20. */
  21. private $_user;
  22. /**
  23. * @inheritdoc
  24. */
  25. public function rules()
  26. {
  27. return [
  28. [['passwd', 'passwd_new', 'passwd_repetition'], 'filter', 'filter' => 'trim'],
  29. [['passwd', 'passwd_new', 'passwd_repetition'], 'required'],
  30. [['passwd', 'passwd_new', 'passwd_repetition'], 'string', 'min' => 6, 'max' => 15],
  31. [['passwd_repetition'], 'compare', 'compareAttribute' => 'passwd_new'],// 验证新密码和重复密码是否相等
  32. ['passwd', 'validatePassword'],
  33. ['passwd_new', 'notCompare'],
  34. ];
  35. }
  36. public function attributeLabels()
  37. {
  38. return [
  39. 'passwd' => '原密码',
  40. 'passwd_new' => '新密码',
  41. 'passwd_repetition' => '重复密码',
  42. ];
  43. }
  44. /**
  45. * @param $attribute
  46. */
  47. public function notCompare($attribute)
  48. {
  49. if ($this->passwd == $this->passwd_new) {
  50. $this->addError($attribute, '新密码不能和原密码相同');
  51. }
  52. }
  53. /**
  54. * 验证原密码是否正确
  55. *
  56. * @param $attribute
  57. * @param $params
  58. */
  59. public function validatePassword($attribute, $params)
  60. {
  61. if (!$this->hasErrors()) {
  62. $user = $this->getUser();
  63. if (!$user || !$user->validatePassword($this->passwd)) {
  64. $this->addError($attribute, '原密码不正确');
  65. }
  66. }
  67. }
  68. /**
  69. * 获取用户信息
  70. *
  71. * @return Member|null
  72. */
  73. protected function getUser()
  74. {
  75. if ($this->_user === null) {
  76. /** @var Member $identity */
  77. $this->_user = Yii::$app->user->identity;
  78. }
  79. return $this->_user;
  80. }
  81. }
粤ICP备19079148号