Completed
Push — master ( 40dc0d...5c158a )
by Igor
05:13
created

SignupProviderForm::rules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 1
eloc 9
nc 1
nop 0
1
<?php
2
3
namespace app\models\forms;
4
5
use Yii;
6
use yii\helpers\ArrayHelper;
7
use yii\base\DynamicModel;
8
use app\helpers\Util;
9
use app\models\User;
10
use app\models\UserProfile;
11
use app\models\UserProvider;
12
13
class SignupProviderForm extends \yii\base\Model
14
{
15
    /**
16
     * @var int
17
     */
18
    public $type;
19
    /**
20
     * @var string
21
     */
22
    public $email;
23
    /**
24
     * @var \app\models\User
25
     */
26
    private $user = null;
27
    /**
28
     * @var bool
29
     */
30
    private $verified = false;
31
    /**
32
     * @var array
33
     */
34
    private $data = [];
35
36
    /**
37
     * Form for social auth
38
     *
39
     * @param array $data
40
     * @param array $config
41
     */
42
    public function __construct($data, $config = [])
43
    {
44
        $this->email = ArrayHelper::getValue($data['profile'], 'email');
45
        $this->type = $data['type'];
46
        $this->data = $data;
47
48
        if (ArrayHelper::getValue($data['profile'], 'verified') && !empty($this->email)) {
49
            $this->verified = true;
50
            $this->user = User::findByEmail($this->email);
51
52
            if (!$this->user) {
53
                $this->user = new User();
54
                $this->user->setConfirmed();
55
            }
56
        }
57
58
        if ($this->user === null) {
59
            $this->user = new User();
60
        }
61
62
        parent::__construct($config);
63
    }
64
65
    /**
66
     * @inheritdoc
67
     */
68
    public function rules()
69
    {
70
        return [
71
            ['email', 'filter', 'filter' => 'trim'],
72
            ['email', 'required'],
73
            ['email', 'string', 'max' => 255],
74
            ['email', 'email'],
75
            ['email', 'unique',
76
                'targetClass' => '\app\models\User',
77
                'message' => Yii::t('app.messages', 'This email address has already been taken')
78
            ],
79
        ];
80
    }
81
82
    /**
83
     * @inheritdoc
84
     */
85
    public function attributeLabels()
86
    {
87
        return (new User())->attributeLabels();
88
    }
89
90
    /**
91
     * Is verified?
92
     *
93
     * @return bool
94
     */
95
    public function isVerified()
96
    {
97
        return $this->verified;
98
    }
99
100
    /**
101
     * Save photo
102
     *
103
     * @param \app\models\UserProfile $profile
104
     * @param string $photo
105
     * @return void
106
     */
107
    private function savePhoto($profile, $photo)
108
    {
109
        $file = Util::makeUploadedFile('file', $photo);
110
111
        $model = new DynamicModel(compact('file'));
112
        $model->addRule('file', 'image', $profile->getFileRules('photo', true))->validate();
0 ignored issues
show
Documentation Bug introduced by
The method getFileRules does not exist on object<app\models\UserProfile>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
113
114
        if (!$model->hasErrors()) {
115
            $file = $profile->createFile('photo', $file->tempName, 'photo', true);
0 ignored issues
show
Documentation Bug introduced by
The method createFile does not exist on object<app\models\UserProfile>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
116
            $profile->photo = $file->id;
117
            $profile->save();
118
        }
119
    }
120
121
    /**
122
     * Signs user up
123
     *
124
     * @param bool $validate
125
     * @return \app\models\User
126
     */
127
    public function signup($validate = true)
128
    {
129
        if ($this->validate($validate ? null : [])) {
130
            if ($this->user->isNewRecord) {
131
                $this->user->email = $this->email;
132
                $this->user->addProfile(UserProvider::parseProfile($this->type, $this->data));
133
                $photo = $this->user->profile->photo;
134
            }
135
            $this->user->addProvider(UserProvider::parseProvider($this->type, $this->data));
136
137
            if ($this->user->save()) {
138
                if (isset($photo) && !empty($photo)) {
139
                    $this->savePhoto($this->user->profile, $photo);
140
                }
141
142
                if ($this->user->authorize(true)) {
143
                    return $this->user;
144
                }
145
            } // @codeCoverageIgnore
146
        } // @codeCoverageIgnore
147
148
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by app\models\forms\SignupProviderForm::signup of type app\models\User.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
149
    }
150
151
    /**
152
     * Sends an email with a link, for confirm the email
153
     *
154
     * @return boolean
155
     */
156
    public function sendEmail()
157
    {
158
        if (!User::isTokenValid($this->user->email_confirm_token)) {
159
            $this->user->generateEmailConfirmToken();
160
            $this->user->updateAttributes([
161
                'email_confirm_token' => $this->user->email_confirm_token,
162
                'date_confirm' => $this->user->date_confirm,
163
            ]);
164
        }
165
166
        return Yii::$app->notify->sendMessage(
167
            $this->email,
168
            Yii::t('app.messages', 'Activate Your Account'),
169
            'emailConfirmToken',
170
            ['user' => $this->user]
171
        );
172
    }
173
}
174