guild/frontend/models/SignupForm.php
2023-10-18 10:49:51 +03:00

88 lines
2.2 KiB
PHP
Executable File

<?php
namespace frontend\models;
use common\classes\Debug;
use Yii;
use yii\base\Model;
use common\models\User;
/**
* Signup form
*/
class SignupForm extends Model
{
public $username;
public $email;
public $password;
/**
* {@inheritdoc}
*/
public function rules()
{
return [
['username', 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
/**
* Signs user up.
*
* @return User|null the saved model or null if saving fails
*/
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->save();
$auth = Yii::$app->authManager;
$authorRole = $auth->getRole('user');
$auth->assign($authorRole, $user->id);
if ($user->save()) {
$this->sendEmail($user);
return $user;
} else {
return null;
}
}
/**
* Sends an email with a link, for resetting the password.
*
* @return bool whether the email was send
*/
private function sendEmail(User $user)
{
return Yii::$app->mailer->compose(
['html' => 'signup-html', 'text' => 'signup-text'],
['user' => $this]
)
->setFrom([Yii::$app->params['senderEmail'] => Yii::$app->name . ' robot'])
->setTo($user->email)
->setSubject('Account registration at ' . Yii::$app->name)
->send();
}
}