Completed
Push — master ( e3a872...4cb8be )
by vistart
04:19
created

UsernameForm::changeUsername()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 3
eloc 7
nc 3
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