SignupForm.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace frontend\models;
  3. use Yii;
  4. use yii\base\Model;
  5. use common\models\User;
  6. /**
  7. * Signup form
  8. */
  9. class SignupForm extends Model
  10. {
  11. public $username;
  12. public $email;
  13. public $password;
  14. /**
  15. * {@inheritdoc}
  16. */
  17. public function rules()
  18. {
  19. return [
  20. ['username', 'trim'],
  21. ['username', 'required'],
  22. ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
  23. ['username', 'string', 'min' => 2, 'max' => 255],
  24. ['email', 'trim'],
  25. ['email', 'required'],
  26. ['email', 'email'],
  27. ['email', 'string', 'max' => 255],
  28. ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
  29. ['password', 'required'],
  30. ['password', 'string', 'min' => Yii::$app->params['user.passwordMinLength']],
  31. ];
  32. }
  33. /**
  34. * Signs user up.
  35. *
  36. * @return bool whether the creating new account was successful and email was sent
  37. */
  38. public function signup()
  39. {
  40. if (!$this->validate()) {
  41. return null;
  42. }
  43. $user = new User();
  44. $user->username = $this->username;
  45. $user->email = $this->email;
  46. $user->setPassword($this->password);
  47. $user->generateAuthKey();
  48. $user->generateEmailVerificationToken();
  49. return $user->save() && $this->sendEmail($user);
  50. }
  51. /**
  52. * Sends confirmation email to user
  53. * @param User $user user model to with email should be send
  54. * @return bool whether the email was sent
  55. */
  56. protected function sendEmail($user)
  57. {
  58. return Yii::$app
  59. ->mailer
  60. ->compose(
  61. ['html' => 'emailVerify-html', 'text' => 'emailVerify-text'],
  62. ['user' => $user]
  63. )
  64. ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])
  65. ->setTo($this->email)
  66. ->setSubject('Account registration at ' . Yii::$app->name)
  67. ->send();
  68. }
  69. }