MailerAccount::getDomain()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
namespace backend\models;
3
4
use yii\db\ActiveRecord;
5
use yii\db\ActiveQuery;
6
7
/**
8
 * This is the model class for table "mailer_users".
9
 *
10
 * @property int $id
11
 * @property int $domain_id
12
 * @property string $email
13
 * @property string $password
14
 * @property MailerDomain $domain
15
 */
16
class MailerAccount extends ActiveRecord implements LoggableInterface
17
{
18
    const PASSWORD_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
19
20
    const PASSWORD_LENGTH = 8;
21
22
    /**
23
     * @inheritdoc
24
     */
25
    public static function tableName()
26
    {
27
        return '{{%mailer_users}}';
28
    }
29
30
    /**
31
     * @inheritdoc
32
     */
33
    public function rules()
34
    {
35
        return [
36
            [['domain_id', 'email'], 'required'],
37
            [['domain_id'], 'exist', 'targetClass' => MailerDomain::class, 'targetAttribute' => 'id'],
38
            [['email'], 'string', 'max' => 120],
39
            [['email'], 'filter', 'filter' => function ($value) {
40
                return $value . '@' . $this->domain->name;
41
            }],
42
            [['email'], 'unique', 'targetAttribute' => ['domain_id', 'email'], 'message' => 'Email is not unique'],
43
        ];
44
    }
45
46
    /**
47
     * @return ActiveQuery
48
     */
49
    public function getDomain()
50
    {
51
        return $this->hasOne(MailerDomain::class, ['id' => 'domain_id']);
52
    }
53
54
    /**
55
     * Generates new password hash and sets it to the model
56
     * @return string
57
     */
58
    public function generatePassword()
59
    {
60
        $this->password = $this->generatePasswordHash(
61
            $password = $this->randomPassword()
62
        );
63
        return $password;
64
    }
65
66
    /**
67
     * @inheritdoc
68
     */
69
    public function attributeLabels()
70
    {
71
        return [
72
            'id' => 'ID',
73
            'domain_id' => 'Domain',
74
            'email' => 'Email',
75
            'password' => 'Change Password',
76
        ];
77
    }
78
79
    protected function generatePasswordHash($string)
80
    {
81
        return crypt($string, '$6$'.substr(md5(rand(1, 10000)), -16));
82
    }
83
84
    protected function randomPassword($length = self::PASSWORD_LENGTH)
85
    {
86
        return substr(str_shuffle(str_repeat(self::PASSWORD_CHARS, 3)), 0, $length);
87
    }
88
}
89