Total Complexity | 65 |
Total Lines | 597 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like User often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use User, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
37 | class User extends ActiveRecord implements IdentityInterface, UserInterface |
||
38 | { |
||
39 | const STATUS_DELETED = 0; |
||
40 | const STATUS_ACTIVE = 10; |
||
41 | |||
42 | const ROLE_USER = 10; |
||
43 | |||
44 | const CONFIRMED_STRING = '_confirmed'; |
||
45 | |||
46 | public $user_behavior; |
||
47 | public $question; |
||
48 | public $time; |
||
49 | |||
50 | public function __construct(UserBehaviorInterface $user_behavior, QuestionInterface $question, TimeInterface $time, $config = []) { |
||
51 | $this->user_behavior = $user_behavior; |
||
52 | $this->question = $question; |
||
53 | $this->time = $time; |
||
54 | parent::__construct($config); |
||
55 | } |
||
56 | |||
57 | public function afterFind() { |
||
58 | $this->time = new \common\components\Time($this->timezone); |
||
59 | parent::afterFind(); |
||
60 | } |
||
61 | |||
62 | public function afterRefresh() { |
||
63 | $this->time = new \common\components\Time($this->timezone); |
||
64 | parent::afterRefresh(); |
||
65 | } |
||
66 | |||
67 | //public function afterSave() { |
||
68 | // $this->time = new \common\components\Time($this->timezone); |
||
69 | // parent::afterSave(); |
||
70 | //} |
||
71 | |||
72 | /** |
||
73 | * @inheritdoc |
||
74 | */ |
||
75 | |||
76 | public function behaviors() |
||
77 | { |
||
78 | return [ |
||
79 | 'timestamp' => [ |
||
80 | 'class' => yii\behaviors\TimestampBehavior::class, |
||
81 | 'attributes' => [ |
||
82 | ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'], |
||
83 | ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'], |
||
84 | ], |
||
85 | ], |
||
86 | ]; |
||
87 | } |
||
88 | |||
89 | /** |
||
90 | * @inheritdoc |
||
91 | */ |
||
92 | public function rules() |
||
93 | { |
||
94 | return [ |
||
95 | ['status', 'default', 'value' => self::STATUS_ACTIVE], |
||
96 | ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]], |
||
97 | |||
98 | ['role', 'default', 'value' => self::ROLE_USER], |
||
99 | ['role', 'in', 'range' => [self::ROLE_USER]], |
||
100 | ]; |
||
101 | } |
||
102 | |||
103 | public function getPartnerEmails() { |
||
104 | return [ |
||
105 | $this->partner_email1, |
||
106 | $this->partner_email2, |
||
107 | $this->partner_email3, |
||
108 | ]; |
||
109 | } |
||
110 | |||
111 | /** |
||
112 | * @inheritdoc |
||
113 | */ |
||
114 | public static function findIdentity($id) |
||
115 | { |
||
116 | return static::findOne($id); |
||
|
|||
117 | } |
||
118 | |||
119 | /** |
||
120 | * @inheritdoc |
||
121 | */ |
||
122 | public static function findIdentityByAccessToken($token, $type = null) |
||
123 | { |
||
124 | throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.'); |
||
125 | } |
||
126 | |||
127 | /** |
||
128 | * Finds user by email |
||
129 | * |
||
130 | * @param string $email |
||
131 | * @return static|null |
||
132 | */ |
||
133 | public function findByEmail($email) |
||
134 | { |
||
135 | return $this->findOne(['email' => $email, 'status' => self::STATUS_ACTIVE]); |
||
136 | } |
||
137 | |||
138 | /** |
||
139 | * Finds user by password reset token |
||
140 | * |
||
141 | * @param string $token password reset token |
||
142 | * @return static|null |
||
143 | */ |
||
144 | public function findByPasswordResetToken($token) |
||
145 | { |
||
146 | if(!$this->isTokenCurrent($token)) { |
||
147 | return null; |
||
148 | } |
||
149 | |||
150 | return $this->findOne([ |
||
151 | 'password_reset_token' => $token, |
||
152 | 'status' => self::STATUS_ACTIVE, |
||
153 | ]); |
||
154 | } |
||
155 | |||
156 | /** |
||
157 | * Finds user by email verification token |
||
158 | * |
||
159 | * @param string $token email verification token |
||
160 | * @return static|null |
||
161 | */ |
||
162 | public function findByVerifyEmailToken($token) |
||
163 | { |
||
164 | if($this->isTokenConfirmed($token)) return null; |
||
165 | |||
166 | $user = $this->findOne([ |
||
167 | 'verify_email_token' => [$token, $token . self::CONFIRMED_STRING], |
||
168 | 'status' => self::STATUS_ACTIVE, |
||
169 | ]); |
||
170 | |||
171 | if($user) { |
||
172 | if(!$this->isTokenConfirmed($token) && |
||
173 | !$this->isTokenCurrent($token, 'user.verifyAccountTokenExpire')) { |
||
174 | return null; |
||
175 | } |
||
176 | } |
||
177 | |||
178 | return $user; |
||
179 | } |
||
180 | |||
181 | /** |
||
182 | * Finds user by email change token |
||
183 | * |
||
184 | * @param string $token email change token |
||
185 | * @return static|null |
||
186 | */ |
||
187 | public function findByChangeEmailToken($token) |
||
188 | { |
||
189 | $user = static::findOne([ |
||
190 | 'change_email_token' => $token, |
||
191 | 'status' => self::STATUS_ACTIVE, |
||
192 | ]); |
||
193 | |||
194 | if($user) { |
||
195 | if(!$user->isTokenCurrent($token, 'user.verifyAccountTokenExpire')) { |
||
196 | return null; |
||
197 | } |
||
198 | } |
||
199 | |||
200 | return $user; |
||
201 | } |
||
202 | |||
203 | /** |
||
204 | * Finds out if a token is current or expired |
||
205 | * |
||
206 | * @param string $token verification token |
||
207 | * @param string $paramPath Yii app param path |
||
208 | * @return boolean |
||
209 | */ |
||
210 | public function isTokenCurrent($token, String $paramPath = 'user.passwordResetTokenExpire') { |
||
211 | $expire = \Yii::$app->params[$paramPath]; |
||
212 | $parts = explode('_', $token); |
||
213 | $timestamp = (int) end($parts); |
||
214 | if ($timestamp + $expire < time()) { |
||
215 | // token expired |
||
216 | return false; |
||
217 | } |
||
218 | return true; |
||
219 | } |
||
220 | |||
221 | /* |
||
222 | * Checks if $token ends with the $match string |
||
223 | * |
||
224 | * @param string $token verification token (the haystack) |
||
225 | * @param string $match the needle to search for |
||
226 | */ |
||
227 | public function isTokenConfirmed($token = null, String $match = self::CONFIRMED_STRING) { |
||
228 | if(is_null($token)) $token = $this->verify_email_token; |
||
229 | return substr($token, -strlen($match)) === $match; |
||
230 | } |
||
231 | |||
232 | /** |
||
233 | * @inheritdoc |
||
234 | */ |
||
235 | public function getId() |
||
236 | { |
||
237 | return $this->getPrimaryKey(); |
||
238 | } |
||
239 | |||
240 | /** |
||
241 | * @inheritdoc |
||
242 | */ |
||
243 | public function getAuthKey() |
||
244 | { |
||
245 | return $this->auth_key; |
||
246 | } |
||
247 | |||
248 | public function getTimezone() { |
||
249 | return $this->timezone; |
||
250 | } |
||
251 | |||
252 | public function isVerified() { |
||
253 | if(is_null($this->verify_email_token)) { |
||
254 | // for old users who verified their accounts before the addition of |
||
255 | // '_confirmed' to the token |
||
256 | return true; |
||
257 | } else { |
||
258 | return !!$this->verify_email_token && $this->isTokenConfirmed($this->verify_email_token); |
||
259 | } |
||
260 | } |
||
261 | |||
262 | /** |
||
263 | * @inheritdoc |
||
264 | */ |
||
265 | public function validateAuthKey($authKey) |
||
268 | } |
||
269 | |||
270 | /** |
||
271 | * Validates password |
||
272 | * |
||
273 | * @param string $password password to validate |
||
274 | * @return boolean if password provided is valid for current user |
||
275 | */ |
||
276 | public function validatePassword($password) |
||
277 | { |
||
278 | return Yii::$app |
||
279 | ->getSecurity() |
||
280 | ->validatePassword($password, $this->password_hash); |
||
281 | } |
||
282 | |||
283 | /** |
||
284 | * Generates password hash from password and sets it to the model |
||
285 | * |
||
286 | * @param string $password |
||
287 | */ |
||
288 | public function setPassword($password) |
||
289 | { |
||
290 | $this->password_hash = Yii::$app |
||
291 | ->getSecurity() |
||
292 | ->generatePasswordHash($password); |
||
293 | } |
||
294 | |||
295 | /** |
||
296 | * Generates email verification token |
||
297 | */ |
||
298 | public function generateVerifyEmailToken() |
||
301 | } |
||
302 | |||
303 | /** |
||
304 | * Confirms email verification token |
||
305 | */ |
||
306 | public function confirmVerifyEmailToken() |
||
307 | { |
||
308 | $this->verify_email_token .= self::CONFIRMED_STRING; |
||
309 | } |
||
310 | |||
311 | /** |
||
312 | * Removes email verification token |
||
313 | */ |
||
314 | public function removeVerifyEmailToken() |
||
315 | { |
||
316 | $this->verify_email_token = null; |
||
317 | } |
||
318 | |||
319 | /** |
||
320 | * Generates email change tokens |
||
321 | */ |
||
322 | public function generateChangeEmailToken() { |
||
324 | } |
||
325 | |||
326 | /** |
||
327 | * Removes change email token |
||
328 | */ |
||
329 | public function removeChangeEmailToken() |
||
330 | { |
||
331 | $this->change_email_token = null; |
||
332 | } |
||
333 | |||
334 | /** |
||
335 | * Generates "remember me" authentication key |
||
336 | */ |
||
337 | public function generateAuthKey() |
||
338 | { |
||
339 | $this->auth_key = Yii::$app |
||
340 | ->getSecurity() |
||
341 | ->generateRandomString(); |
||
342 | } |
||
343 | |||
344 | /** |
||
345 | * Generates new password reset token |
||
346 | */ |
||
347 | public function generatePasswordResetToken() |
||
348 | { |
||
349 | $this->password_reset_token = $this->getRandomVerifyString(); |
||
350 | } |
||
351 | |||
352 | /** |
||
353 | * Removes password reset token |
||
354 | */ |
||
355 | public function removePasswordResetToken() |
||
358 | } |
||
359 | |||
360 | public function sendEmailReport($date) { |
||
361 | if(!$this->send_email) return false; // no partner emails set |
||
362 | list($start, $end) = $this->time->getUTCBookends($date); |
||
363 | //$scores_of_month = $this->user_behavior->calculateScoresOfLastMonth(); |
||
364 | $graph = Yii::$container |
||
365 | ->get(\common\components\Graph::class) |
||
366 | ->create([]); |
||
367 | $user_behaviors = $this->getUserBehaviors($date); |
||
368 | $user_questions = $this->getUserQuestions($date); |
||
369 | |||
370 | $messages = []; |
||
371 | foreach($this->getPartnerEmails() as $email) { |
||
372 | if($email) { |
||
373 | $messages[] = Yii::$app->mailer->compose('checkinReport', [ |
||
374 | 'user' => $this, |
||
375 | 'email' => $email, |
||
376 | 'date' => $date, |
||
377 | 'user_behaviors' => $user_behaviors, |
||
378 | 'questions' => $user_questions, |
||
379 | 'chart_content' => $graph, |
||
380 | 'categories' => \common\models\Category::$categories, |
||
381 | 'behaviors_list' => \common\models\Behavior::$behaviors, |
||
382 | ])->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name]) |
||
383 | ->setReplyTo($this->email) |
||
384 | ->setSubject($this->email." has completed a Faster Scale check-in") |
||
385 | ->setTo($email); |
||
386 | } |
||
387 | } |
||
388 | |||
389 | return Yii::$app->mailer->sendMultiple($messages); |
||
390 | } |
||
391 | |||
392 | public function getExportData() { |
||
393 | $query = (new Query) |
||
394 | ->select( |
||
395 | 'l.id, |
||
396 | l.date AS "date", |
||
397 | l.behavior_id AS "behavior_id", |
||
398 | (SELECT q1.answer |
||
399 | FROM question q1 |
||
400 | WHERE q1.question = 1 |
||
401 | AND q1.user_behavior_id = l.id) AS "question1", |
||
402 | (SELECT q1.answer |
||
403 | FROM question q1 |
||
404 | WHERE q1.question = 2 |
||
405 | AND q1.user_behavior_id = l.id) AS "question2", |
||
406 | (SELECT q1.answer |
||
407 | FROM question q1 |
||
408 | WHERE q1.question = 3 |
||
409 | AND q1.user_behavior_id = l.id) AS "question3"') |
||
410 | ->from('user_behavior_link l') |
||
411 | ->join("LEFT JOIN", "question q", "l.id = q.user_behavior_id") |
||
412 | ->where('l.user_id=:user_id', ["user_id" => Yii::$app->user->id]) |
||
413 | ->groupBy('l.id, |
||
414 | l.date, |
||
415 | "question1", |
||
416 | "question2", |
||
417 | "question3"') |
||
418 | ->orderBy('l.date DESC'); |
||
419 | |||
420 | return $query |
||
421 | ->createCommand() |
||
422 | ->query(); |
||
423 | |||
424 | /* Plaintext Query |
||
425 | SELECT l.id, |
||
426 | l.date AS "date", |
||
427 | l.behavior_id AS "behavior_id", |
||
428 | (SELECT q1.answer |
||
429 | FROM question q1 |
||
430 | WHERE q1.question = 1 |
||
431 | AND q1.user_behavior_id = l.id) AS "question1", |
||
432 | (SELECT q1.answer |
||
433 | FROM question q1 |
||
434 | WHERE q1.question = 2 |
||
435 | AND q1.user_behavior_id = l.id) AS "question2", |
||
436 | (SELECT q1.answer |
||
437 | FROM question q1 |
||
438 | WHERE q1.question = 3 |
||
439 | AND q1.user_behavior_id = l.id) AS "question3" |
||
440 | FROM user_behavior_link l |
||
441 | LEFT JOIN question q |
||
442 | ON l.id = q.user_behavior_id |
||
443 | WHERE l.user_id = 1 |
||
444 | GROUP BY l.id, |
||
445 | l.date, |
||
446 | "question1", |
||
447 | "question2", |
||
448 | "question3", |
||
449 | ORDER BY l.date DESC; |
||
450 | */ |
||
451 | } |
||
452 | |||
453 | public function sendSignupNotificationEmail() { |
||
454 | return \Yii::$app->mailer->compose('signupNotification') |
||
455 | ->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name]) |
||
456 | ->setTo(\Yii::$app->params['adminEmail']) |
||
457 | ->setSubject('A new user has signed up for '.\Yii::$app->name) |
||
458 | ->send(); |
||
459 | } |
||
460 | |||
461 | public function sendVerifyEmail() { |
||
462 | return \Yii::$app->mailer->compose('verifyEmail', ['user' => $this]) |
||
463 | ->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name]) |
||
464 | ->setTo($this->email) |
||
465 | ->setSubject('Please verify your '.\Yii::$app->name .' account') |
||
466 | ->send(); |
||
467 | } |
||
468 | |||
469 | public function sendDeleteNotificationEmail() { |
||
470 | $messages = []; |
||
471 | foreach(array_merge([$this->email], $this->getPartnerEmails()) as $email) { |
||
472 | if($email) { |
||
473 | $messages[] = Yii::$app->mailer->compose('deleteNotification', [ |
||
474 | 'user' => $this, |
||
475 | 'email' => $email |
||
476 | ])->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name]) |
||
477 | ->setReplyTo($this->email) |
||
478 | ->setSubject($this->email." has deleted their The Faster Scale App account") |
||
479 | ->setTo($email); |
||
480 | } |
||
481 | } |
||
482 | |||
483 | return Yii::$app->mailer->sendMultiple($messages); |
||
484 | } |
||
485 | |||
486 | public function getUserQuestions($local_date = null) { |
||
487 | if(is_null($local_date)) $local_date = $this->time->getLocalDate(); |
||
488 | $questions = $this->getQuestionData($local_date); |
||
489 | return $this->parseQuestionData($questions); |
||
490 | } |
||
491 | |||
492 | public function getUserBehaviors($local_date = null) { |
||
493 | if(is_null($local_date)) $local_date = $this->time->getLocalDate(); |
||
494 | |||
495 | $behaviors = $this->getBehaviorData($local_date); |
||
496 | $behaviors = $this->user_behavior::decorateWithCategory($behaviors); |
||
497 | return $this->parseBehaviorData($behaviors); |
||
498 | } |
||
499 | |||
500 | public function parseQuestionData($questions) { |
||
501 | if(!$questions) return []; |
||
502 | |||
503 | $question_answers = []; |
||
504 | foreach($questions as $question) { |
||
505 | $behavior = $question['behavior']; |
||
506 | |||
507 | $question_answers[$behavior['id']]['question'] = [ |
||
508 | "id" => $behavior['id'], |
||
509 | "title" => $behavior['name'] |
||
510 | ]; |
||
511 | |||
512 | $question_answers[$behavior['id']]["answers"][] = [ |
||
513 | "title" => $this->question::$QUESTIONS[$question['question']], |
||
514 | "answer" => $question['answer'] |
||
515 | ]; |
||
516 | } |
||
517 | |||
518 | return $question_answers; |
||
519 | } |
||
520 | |||
521 | public function parseBehaviorData($behaviors) { |
||
522 | if(!$behaviors) return []; |
||
523 | |||
524 | $opts_by_cat = []; |
||
525 | foreach($behaviors as $behavior) { |
||
526 | $indx = $behavior['behavior']['category_id']; |
||
527 | |||
528 | $opts_by_cat[$indx]['category_name'] = $behavior['behavior']['category']['name']; |
||
529 | $opts_by_cat[$indx]['behaviors'][] = [ |
||
530 | "id" => $behavior['behavior_id'], |
||
531 | "name"=>$behavior['behavior']['name']]; |
||
532 | } |
||
533 | |||
534 | return $opts_by_cat; |
||
535 | } |
||
536 | |||
537 | public function getQuestionData($local_date) { |
||
538 | list($start, $end) = $this->time->getUTCBookends($local_date); |
||
539 | |||
540 | $questions = $this->question->find() |
||
541 | ->where("user_id=:user_id |
||
542 | AND date > :start_date |
||
543 | AND date < :end_date", |
||
544 | [ |
||
545 | "user_id" => Yii::$app->user->id, |
||
546 | ':start_date' => $start, |
||
547 | ":end_date" => $end |
||
548 | ]) |
||
549 | ->asArray() |
||
550 | ->all(); |
||
551 | |||
552 | $questions = $this->user_behavior::decorate($questions); |
||
553 | |||
554 | return $questions; |
||
555 | } |
||
556 | |||
557 | public function getBehaviorData($local_date) { |
||
558 | list($start, $end) = $this->time->getUTCBookends($local_date); |
||
559 | |||
560 | return $this->user_behavior->find() |
||
561 | ->where("user_id=:user_id |
||
562 | AND date > :start_date |
||
563 | AND date < :end_date", |
||
564 | [ |
||
565 | "user_id" => Yii::$app->user->id, |
||
566 | ':start_date' => $start, |
||
567 | ":end_date" => $end |
||
568 | ]) |
||
569 | ->asArray() |
||
570 | ->all(); |
||
571 | } |
||
572 | |||
573 | public function cleanExportData($data) { |
||
574 | $order = array_flip(["date", "behavior", "category", "question1", "question2", "question3"]); |
||
575 | |||
576 | $ret = array_map( |
||
577 | function($row) use ($order) { |
||
578 | // change timestamp to local time (for the user) |
||
579 | $row['date'] = $this->time->convertUTCToLocal($row['date'], false); |
||
580 | |||
581 | // clean up things we don't need |
||
582 | $row['category'] = $row['behavior']['category']['name']; |
||
583 | $row['behavior'] = $row['behavior']['name']; |
||
584 | unset($row['id']); |
||
585 | unset($row['behavior_id']); |
||
586 | |||
587 | // sort the array into a sensible order |
||
588 | uksort($row, function($a, $b) use ($order) { |
||
589 | return $order[$a] <=> $order[$b]; |
||
590 | }); |
||
591 | return $row; |
||
592 | }, |
||
593 | $data |
||
594 | ); |
||
595 | return $ret; |
||
596 | } |
||
597 | |||
598 | /* |
||
599 | * getIdHash() |
||
600 | * |
||
601 | * @return String a user-identifying hash |
||
602 | * |
||
603 | * After generating the hash, we run it through a url-safe base64 encoding to |
||
604 | * shorten it. This generated string is currently used as an identifier in |
||
605 | * URLs, so the shorter the better. the url-safe version has been ripped from |
||
606 | * https://secure.php.net/manual/en/function.base64-encode.php#103849 |
||
607 | * |
||
608 | * It does NOT take into account the user's email address. The email address |
||
609 | * is changeable by the user. If that was used for this function, the |
||
610 | * returned hash would change when the user updates their email. That would |
||
611 | * obviously not be desirable. |
||
612 | */ |
||
613 | public function getIdHash() { |
||
614 | return rtrim( |
||
615 | strtr( |
||
616 | base64_encode( |
||
617 | hash('sha256', $this->id."::".$this->created_at, true) |
||
618 | ), |
||
619 | '+/', '-_'), |
||
620 | '='); |
||
621 | } |
||
622 | |||
623 | /* |
||
624 | * getRandomVerifyString() |
||
625 | * |
||
626 | * @return String a randomly generated string with a timestamp appended |
||
627 | * |
||
628 | * This is generally used for verification purposes: verifying an email, password change, or email address change. |
||
629 | */ |
||
630 | private function getRandomVerifyString() { |
||
634 | } |
||
635 | } |
||
636 |
In the issue above, the returned value is violating the contract defined by the mentioned interface.
Let's take a look at an example: