Passed
Push — master ( 4cb8be...c709fd )
by vistart
04:21
created

UsernameForm::attributeLabels()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 - 2017 vistart
10
 * @license https://vistart.me/license/
11
 */
12
13
namespace rhosocial\user\forms;
14
15
use rhosocial\user\User;
16
use yii\web\Model;
17
18
/**
19
 * Class UsernameForm
20
 * @package rhosocial\user\forms
21
 * @version 1.0
22
 * @author vistart <[email protected]>
23
 */
24
class UsernameForm extends Model
25
{
26
    /**
27
     * @var User
28
     */
29
    public $user;
30
    public $username;
31
32
    /**
33
     * @return mixed
34
     */
35
    protected function getNoInitUsername()
36
    {
37
        $class = $this->user->usernameClass;
38
        return $class::buildNoInitModel();
39
    }
40
41
    /**
42
     * @return array
43
     */
44
    public function rules()
45
    {
46
        return [
47
            ['username', 'required'],
48
            ['username', 'string', 'max' => 32, 'min' => '2'],
49
            ['username', 'match', 'not' => true, 'pattern' => '/^\d+$/', 'message' => Yii::t('user', 'The username can not be a pure number.')],
50
            ['username', 'match', 'pattern' => '/^\w{2,32}$/'],
51
            ['username', 'unique', 'targetClass' => $this->user->usernameClass, 'targetAttribute' => $this->getNoInitUsername()->contentAttribute],
52
        ];
53
    }
54
55
    /**
56
     * Change username.
57
     * @return bool
58
     */
59
    public function changeUsername()
60
    {
61
        if ($this->validate()) {
62
            $username = $this->user->createUsername($this->username);
63
            if (!$username) {
64
                return false;
65
            }
66
            return $username->save();
67
        }
68
        return false;
69
    }
70
71
    /**
72
     * @return array
73
     */
74
    public function attributeLabels()
75
    {
76
        return [
77
            'username' => Yii::t('user', 'Username'),
78
        ];
79
    }
80
81
    /**
82
     * @inheritdoc
83
     */
84
    public function attributeHints()
85
    {
86
        return [
87
            'username' => Yii::t('user', 'Specify a username to provide convenience for login.'),
88
        ];
89
    }
90
}
91