/
FormRegister.php
117 lines (102 loc) · 3 KB
/
FormRegister.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
namespace Apps\Model\Front\User;
use Apps\ActiveRecord\Profile;
use Apps\ActiveRecord\User;
use Ffcms\Core\App;
use Ffcms\Core\Arch\Model;
use Ffcms\Core\Helper\Crypt;
/**
* Class FormRegister. User registration business logic model
* @package Apps\Model\Front\User
*/
class FormRegister extends Model
{
public $email;
public $password;
public $repassword;
public $captcha;
private $_captcha = false;
/** @var User|null */
public $_userObject;
/** @var Profile|null */
public $_profileObject;
/**
* FormRegister constructor. Build model and set maker if captcha is enabled
* @param bool $captcha
*/
public function __construct($captcha = false)
{
$this->_captcha = $captcha;
parent::__construct(true);
}
/**
* Validation rules
* @return array
*/
public function rules(): array
{
$rules = [
[['password', 'repassword', 'email'], 'required'],
['password', 'length_min', '3'],
['email', 'email'],
['repassword', 'equal', $this->getRequest('password', $this->getSubmitMethod())],
['captcha', 'used']
];
if ($this->_captcha) {
$rules[] = ['captcha', 'App::$Captcha::validate'];
}
return $rules;
}
/**
* Labels for form items
* @return array
*/
public function labels(): array
{
return [
'password' => __('Password'),
'repassword' => __('Repeat password'),
'email' => __('Email'),
'captcha' => __('Captcha')
];
}
/**
* Try to insert user data in database
* @param bool $activation
* @return bool
*/
public function tryRegister($activation = false): bool
{
$check = App::$User->where('email', $this->email)
->count();
if ($check !== 0) {
return false;
}
// create row
$user = new User();
$user->email = $this->email;
$user->password = Crypt::passwordHash($this->password);
// if need to be approved - make random token and send email
if ($activation) {
$user->approve_token = Crypt::randomString(mt_rand(32, 128)); // random token for validation url
// send email
if (App::$Mailer) {
App::$Mailer->tpl('user/_mail/approve', [
'token' => $user->approve_token,
'email' => $user->email
])->send($this->email, (new \Swift_Message(App::$Translate->get('Default', 'Registration approve', []))));
}
}
// save row
$user->save();
// create profile
$profile = new Profile();
$profile->user_id = $user->id;
// save profile
$profile->save();
// set user & profile objects to attributes to allow extending this model
$this->_userObject = $user;
$this->_profileObject = $profile;
return true;
}
}