<?php
namespace app\models;
use app\components\NewUserEvent;
use app\components\Notifications;
use yii\base\Model;
use app\models\User;
/**
* Signup form
*/
class Register extends Model {
const EVENT_NEW_USER = 'new-user';
public $username;
public $email;
public $phone;
public $password;
public $password_repeat;
public $verifyCode;
/**
* @inheritdoc
*/
public function rules()
{
return [
['phone', 'trim'],
['phone', 'required'],
['phone', 'string', 'min' => 10],
['phone', 'unique', 'targetClass' => '\app\models\User', 'message' => 'Телефон занят'],
['username', 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\app\models\User', 'message' => 'Логин занят'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'Email адрес занят'],
['password', 'required'],
['password_repeat', 'required'],
['password', 'string', 'min' => 6],
['password_repeat', 'compare', 'compareAttribute' => 'password'],
['verifyCode', 'captcha', 'message' => 'Код введен неверно'],
];
}
/**
* @param \app\models\User $user
* @param NewUserEvent $event
* @return \app\models\User|null
*/
public function register( User $user, NewUserEvent $event)
{
if ( !$this->validate() ) {
return null;
}
$user->username = $this->username;
$user->email = $this->email;
$user->phone = str_replace(['+', '(', ')' , ' '], '', $this->phone);
$user->setPassword($this->password);
$user->generateAuthKey();
if( $user->save() ) {
$event->username = $user->username;
$event->phone = $user->phone;
$event->email = $user->email;
$event->password = $this->password;
$this->trigger(self::EVENT_NEW_USER, $event);
return $user;
}
return null;
}
}
//user model
public function init() {
$this->on(self::EVENT_NEW_USER, function ($event) {
$a = new Notifications();
$a->sendEmail('example', 'Новый пользователь', [$this->email => $this->username], ['login' => $this->username, 'password' => $this->password]);
});
}