Completed
Push — master ( 92c153...24a31f )
by Igor
10:25
created

SignupProviderForm::signup()   C

Complexity

Conditions 8
Paths 11

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 8

Importance

Changes 6
Bugs 2 Features 2
Metric Value
c 6
b 2
f 2
dl 0
loc 23
ccs 13
cts 13
cp 1
rs 6.1403
cc 8
eloc 13
nc 11
nop 1
crap 8
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 string
17
     */
18
    public $email;
19
    /**
20
     * @var \app\models\User
21
     */
22
    private $user = null;
23
    /**
24
     * @var bool
25
     */
26
    private $verifiedEmail = false;
27
    /**
28
     * @var array
29
     */
30
    private $provider = null;
31
32 6
    public function __construct($provider)
33
    {
34 6
        $this->provider = $provider;
35 6
    }
36
37
    /**
38
     * @inheritdoc
39
     */
40 6
    public function rules()
41
    {
42
        return [
43 6
            ['email', 'filter', 'filter' => 'trim'],
44
            ['email', 'required'],
45
            ['email', 'string', 'max' => 255],
46
            ['email', 'email'],
47 6
            ['email', 'unique',
48 6
                'targetClass' => '\app\models\User',
49 6
                'message' => Yii::t('app.validators', 'This email address has already been taken')
50
            ],
51
        ];
52
    }
53
54
    /**
55
     * @inheritdoc
56
     */
57 5
    public function attributeLabels()
58
    {
59 5
        return (new User())->attributeLabels();
60
    }
61
62
    /**
63
     * Is verified?
64
     *
65
     * @return bool
66
     */
67 6
    public function isVerifiedEmail()
68
    {
69 6
        return $this->verifiedEmail;
70
    }
71
72
    /**
73
     * Prepare user
74
     */
75 6
    public function prepareUser()
76
    {
77 6
        $profile = $this->provider['profile'];
78 6
        $this->email = ArrayHelper::getValue($profile, 'email');
79 6
        $isVerifiedEmail = ArrayHelper::getValue($profile, 'verified');
80
81 6
        if ($isVerifiedEmail && !empty($this->email)) {
82 1
            $this->verifiedEmail = true;
83 1
            $this->user = User::findByEmail($this->email);
84
85 1
            if (!$this->user) {
86 1
                $this->user = new User();
87 1
                $this->user->setConfirmed();
88
            }
89
        }
90
91 6
        if ($this->user === null) {
92 5
            $this->user = new User();
93
        }
94 6
    }
95
96
    /**
97
     * Parse provider
98
     *
99
     * @return array
100
     */
101 4
    public function parseProvider()
102
    {
103 4
        $provider = [];
104 4
        switch ($this->provider['type']) {
105 4
            case UserProvider::TYPE_FACEBOOK:
106 1
                $provider = $this->parseProviderFacebook();
107 1
                break;
108
109 3
            case UserProvider::TYPE_VKONTAKTE:
110 2
                $provider = $this->parseProviderVkontakte();
111 2
                break;
112
113 1
            case UserProvider::TYPE_TWITTER:
114 1
                $provider = $this->parseProviderTwitter();
115 1
                break;
116
        }
117 4
        $provider['type'] = $this->provider['type'];
118 4
        return $provider;
119
    }
120
121
    /**
122
     * Parse profile
123
     *
124
     * @return array
125
     */
126 4
    public function parseProfile()
127
    {
128 4
        $profile = [];
129 4
        switch ($this->provider['type']) {
130 4
            case UserProvider::TYPE_FACEBOOK:
131 1
                $profile = $this->parseProfileFacebook();
132 1
                break;
133
134 3
            case UserProvider::TYPE_VKONTAKTE:
135 2
                $profile = $this->parseProfileVkontakte();
136 2
                break;
137
138 1
            case UserProvider::TYPE_TWITTER:
139 1
                $profile = $this->parseProfileTwitter();
140 1
                break;
141
        }
142 4
        $profile['type'] = $this->provider['type'];
143 4
        return $profile;
144
    }
145
146
    /**
147
     * Prepare provider attributes for facebook
148
     *
149
     * @return array
150
     */
151 1
    private function parseProviderFacebook()
152
    {
153 1
        $profile = $this->provider['profile'];
154
        return [
155 1
            'profile_id' => $profile['id'],
156 1
            'profile_url' => $profile['link'],
157 1
            'access_token' => $this->provider['token']['access_token'],
158 1
            'access_token_secret' => ''
159
        ];
160
    }
161
162
    /**
163
     * Prepare provider attributes for vkontakte
164
     *
165
     * @return array
166
     */
167 2
    private function parseProviderVkontakte()
168
    {
169 2
        $profile = $this->provider['profile'];
170
        return [
171 2
            'profile_id' => $profile['id'],
172 2
            'profile_url' => 'https://vk.com/id' . $profile['id'],
173 2
            'access_token' => $this->provider['token']['access_token'],
174 2
            'access_token_secret' => ''
175
        ];
176
    }
177
178
    /**
179
     * Prepare provider attributes for twitter
180
     *
181
     * @return array
182
     */
183 1
    private function parseProviderTwitter()
184
    {
185 1
        $profile = $this->provider['profile'];
186
        return [
187 1
            'profile_id' => $profile['id'],
188 1
            'profile_url' => 'https://twitter.com/' . $profile['screen_name'],
189 1
            'access_token' => $this->provider['token']['oauth_token'],
190 1
            'access_token_secret' => $this->provider['token']['oauth_token_secret']
191
        ];
192
    }
193
194
    /**
195
     * Prepare profile attributes for facebook
196
     *
197
     * @return array
198
     */
199 1
    private function parseProfileFacebook()
200
    {
201 1
        $profile = $this->provider['profile'];
202
        return [
203 1
            'full_name' => trim($profile['name']),
204 1
            'birth_day' => '—',
205 1
            'photo' => ArrayHelper::getValue($profile, 'picture.data.url', '')
206
        ];
207
    }
208
209
    /**
210
     * Prepare profile attributes for vkontakte
211
     *
212
     * @return array
213
     */
214 2
    private function parseProfileVkontakte()
215
    {
216 2
        $profile = $this->provider['profile'];
217
        return [
218 2
            'full_name' => trim($profile['first_name'] . ' ' . $profile['last_name']),
219 2
            'birth_day' => date_format(
220 2
                date_create_from_format('d.m.Y', $profile['bdate']),
221 2
                'Y-m-d'
222
            ),
223 2
            'photo' => str_replace('_50', '_400', $profile['photo'])
224
        ];
225
    }
226
227
    /**
228
     * Prepare profile attributes for twitter
229
     *
230
     * @param array $data Data from social network
0 ignored issues
show
Bug introduced by
There is no parameter named $data. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
231
     * @return array
232
     */
233 1
    private function parseProfileTwitter()
234
    {
235 1
        $profile = $this->provider['profile'];
236
        return [
237 1
            'full_name' => $profile['name'],
238 1
            'photo' => str_replace('_normal', '_400x400', $profile['profile_image_url'])
239
        ];
240
    }
241
242
    /**
243
     * Save photo
244
     *
245
     * @param \app\models\UserProfile $profile
246
     * @param string $photo
247
     * @return void
248
     */
249 4
    private function savePhoto($profile, $photo)
250
    {
251 4
        $file = Util::makeUploadedFile('file', $photo);
252
253 4
        $model = new DynamicModel(compact('file'));
254 4
        $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...
255
256 4
        if (!$model->hasErrors()) {
257 3
            $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...
258 3
            $profile->photo = $file->id;
259 3
            $profile->save();
260
        }
261 4
    }
262
263
    /**
264
     * Signs user up
265
     *
266
     * @param bool $checkExistEmail
267
     * @return \app\models\User
268
     */
269 6
    public function signup($checkExistEmail = true)
270
    {
271 6
        if ($this->validate($checkExistEmail ? null : [])) {
272 4
            if ($this->user->isNewRecord) {
273 4
                $this->user->email = $this->email;
274 4
                $this->user->addProfile($this->parseProfile());
275 4
                $photo = $this->user->profile->photo;
276
            }
277 4
            $this->user->addProvider($this->parseProvider());
278
279 4
            if ($this->user->save()) {
280 4
                if (isset($photo) && !empty($photo)) {
281 4
                    $this->savePhoto($this->user->profile, $photo);
282
                }
283
284 4
                if ($this->user->authorize(true)) {
285 4
                    return $this->user;
286
                }
287
            } // @codeCoverageIgnore
288
        } // @codeCoverageIgnore
289
290 2
        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...
291
    }
292
293
    /**
294
     * Sends an email with a link, for confirm the email
295
     *
296
     * @return boolean
297
     */
298 3
    public function sendEmail()
299
    {
300 3
        if (!User::isTokenValid($this->user->email_confirm_token)) {
301 3
            $this->user->generateEmailConfirmToken();
302 3
            $this->user->updateAttributes([
303 3
                'email_confirm_token' => $this->user->email_confirm_token,
304 3
                'date_confirm' => $this->user->date_confirm,
305
            ]);
306
        }
307
308 3
        return Yii::$app->notify->sendMessage(
309 3
            $this->email,
310 3
            Yii::t('app', 'Activate Your Account'),
311 3
            'emailConfirmToken',
312 3
            ['user' => $this->user]
313
        );
314
    }
315
}
316