FormInviteSend::labels()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Apps\Model\Admin\User;
4
5
use Apps\ActiveRecord\Invite;
6
use Ffcms\Core\App;
7
use Ffcms\Core\Arch\Model;
8
use Ffcms\Core\Helper\Crypt;
9
10
/**
11
 * Class FormInviteSend. Send user invitation to email
12
 * @package Apps\Model\Admin\User
13
 */
14
class FormInviteSend extends Model
15
{
16
    const TOKEN_VALID_TIME = 604800; // 7 days
17
18
    public $email;
19
20
    /**
21
     * Before execute method. Cleanup deprecated invites
22
     */
23
    public function before()
24
    {
25
        Invite::clean();
26
    }
27
28
    /**
29
     * Form display labels
30
     * @return array
31
     */
32
    public function labels(): array
33
    {
34
        return [
35
            'email' => __('Email')
36
        ];
37
    }
38
39
    /**
40
     * Validation rules
41
     * @return array
42
     */
43
    public function rules(): array
44
    {
45
        return [
46
            ['email', 'required'],
47
            ['email', 'email'],
48
            ['email', 'Apps\Model\Admin\User\FormUserUpdate::isUniqueEmail', null]
49
        ];
50
    }
51
52
    /**
53
     * Send invite to email
54
     * @return bool
55
     */
56
    public function make()
57
    {
58
        $token = $this->makeInvite();
59
        // save data in database
60
        $invObj = new Invite();
61
        $invObj->email = $this->email;
62
        $invObj->token = $token;
63
        $invObj->save();
64
65
        if (App::$Mailer) {
66
            return App::$Mailer->tpl('user/_mail/invite', [
67
                'invite' => $token,
68
                'email' => $this->email
69
            ])->send($this->email, App::$Translate->get('Default', __('You got registration invite'), []));
70
        }
71
72
        return false;
73
    }
74
75
    /**
76
     * Generate unique invite string
77
     * @return string
78
     */
79
    private function makeInvite()
80
    {
81
        $token = Crypt::randomString(mt_rand(32, 128));
82
        $find = Invite::where('token', $token)
83
            ->count();
84
        return $find === 0 ? $token : $this->makeInvite(); // prevent duplication
85
    }
86
}
87