ProfileController::behaviors()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 20
rs 9.7998
cc 1
nc 1
nop 0
1
<?php
2
namespace site\controllers;
3
4
5
use Yii;
6
use common\models\Question;
7
use common\components\Controller;
8
use yii\filters\VerbFilter;
9
use common\components\AccessControl;
10
use League\Csv\Writer;
0 ignored issues
show
Bug introduced by
The type League\Csv\Writer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use yii\web\BadRequestHttpException;
12
13
/**
14
 * Profile controller
15
 */
16
class ProfileController extends Controller {
17
  /**
18
   * @inheritdoc
19
   */
20
  public function behaviors() {
21
    return [
22
      'access' => [
23
        'class' => AccessControl::class,
24
        'rules' => [
25
          [
26
            'actions' => ['index', 'error', 'delete-account', 'change-password', 'request-change-email', 'export'],
27
            'allow'   => true,
28
            'roles'   => ['@'],
29
          ], [
30
            'actions' => [ 'change-email', ],
31
            'allow'   => true,
32
          ],
33
        ],
34
      ],
35
      'verbs' => [
36
        'class' => VerbFilter::class,
37
        'actions' => [
38
          'deleteAccount' => ['post'],
39
          'changePassword' => ['post'],
40
        ],
41
      ],
42
    ];
43
  }
44
45
  public function actionIndex() {
46
    $editProfileForm    = Yii::$container->get(\site\models\EditProfileForm::class, [Yii::$app->user->identity]);
47
    $changePasswordForm = Yii::$container->get(\site\models\ChangePasswordForm::class, [Yii::$app->user->identity]);
48
    $changeEmailForm    = Yii::$container->get(\site\models\ChangeEmailForm::class, [Yii::$app->user->identity]);
49
    $deleteAccountForm  = Yii::$container->get(\site\models\DeleteAccountForm::class, [Yii::$app->user->identity]);
50
    $customBehaviorForm = Yii::$container->get(\site\models\CustomBehaviorForm::class, [Yii::$app->user->identity]);
51
    $graph              = Yii::$container->get(\common\components\Graph::class, [Yii::$app->user->identity]);
52
53
    if (Yii::$app->request->isAjax && $editProfileForm->load($_POST)) {
54
      Yii::$app->response->format = 'json';
55
      return \yii\widgets\ActiveForm::validate($editProfileForm);
56
    }
57
    $editProfileForm->loadUser();
58
59
    if ($editProfileForm->load(Yii::$app->request->post())) {
60
      $saved_user = $editProfileForm->saveProfile();
61
      if($saved_user) {
62
        Yii::$app->session->setFlash('success', 'New profile data saved!');
0 ignored issues
show
Bug introduced by
The method setFlash() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

62
        Yii::$app->session->/** @scrutinizer ignore-call */ 
63
                            setFlash('success', 'New profile data saved!');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
63
      }
64
    }
65
66
    return $this->render('index', [
67
      'profile'         => $editProfileForm,
68
      'change_password' => $changePasswordForm,
69
      'change_email'    => $changeEmailForm,
70
      'delete'          => $deleteAccountForm,
71
      'custom_behavior'=> $customBehaviorForm,
72
      'graph_url'       => $graph->getUrl(Yii::$app->user->identity->getIdHash()),
0 ignored issues
show
Bug introduced by
The method getIdHash() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

72
      'graph_url'       => $graph->getUrl(Yii::$app->user->identity->/** @scrutinizer ignore-call */ getIdHash()),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method getIdHash() does not exist on yii\web\IdentityInterface. Did you maybe mean getId()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

72
      'graph_url'       => $graph->getUrl(Yii::$app->user->identity->/** @scrutinizer ignore-call */ getIdHash()),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
73
      'gridView'        => Yii::$container->get(\common\models\CustomBehavior::class)->getGridView(),
74
    ]);
75
  }
76
77
  public function actionDeleteAccount() {
78
    $model = Yii::$container->get(\site\models\DeleteAccountForm::class, [Yii::$app->user->identity]);
79
80
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
81
      if($model->deleteAccount()) {
82
        $this->redirect(['site/index']);
83
      } else {
84
        Yii::$app->session->setFlash('error', 'Wrong password!');
85
      }
86
    }
87
88
    $this->redirect(Yii::$app->request->getReferrer());
89
  }
90
91
  public function actionChangePassword() {
92
    $model = Yii::$container->get(\site\models\ChangePasswordForm::class, [Yii::$app->user->identity]);
93
94
    if ($model->load(Yii::$app->request->post())) {
95
      if($model->validate() && $model->changePassword()) {
96
        Yii::$app->session->setFlash('success', 'Password successfully changed');
97
      } else {
98
        Yii::$app->session->setFlash('error', 'Wrong password!');
99
      }
100
    }
101
102
    $this->redirect(['profile/index']);
103
  }
104
105
  public function actionRequestChangeEmail() {
106
    $model = Yii::$container->get(\site\models\ChangeEmailForm::class, [Yii::$app->user->identity]);
107
108
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
109
      $model->changeEmail();
110
      Yii::$app->session->setFlash('success', "We've sent an email to your requested email address to confirm. Please click on the verification link to continue.");
111
    }
112
113
    $this->redirect(['profile/index']);
114
  }
115
116
  public function actionChangeEmail(string $token) {
117
    $user = Yii::$container->get(\common\interfaces\UserInterface::class)->findByChangeEmailToken($token);
118
119
    if($user) {
120
      $validator = new \yii\validators\EmailValidator();
121
      if($validator->validate($user->desired_email, $error)) {
122
        $user->removeChangeEmailToken();
123
        $user->email = $user->desired_email;
124
        $user->desired_email = null;
125
        $user->save();
126
        if(!Yii::$app->user->isGuest) {
127
          Yii::$app->user->logout();
0 ignored issues
show
Bug introduced by
The method logout() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

127
          Yii::$app->user->/** @scrutinizer ignore-call */ 
128
                           logout();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
128
          Yii::$app->session->setFlash('success', 'Your email address was successfully changed. For security, we\'ve logged you out.');
129
        } else {
130
          Yii::$app->session->setFlash('success', 'Your email address was successfully changed.');
131
        }
132
        return $this->goHome();
133
      } else {
134
        // desired_email failed validation. Something sneaky might be happening here
135
        Yii::warning("ProfileController::actionChangeEmail() User({$user->id}) desired_email failed validation. Something weird is going on.");
136
        return $this->goHome();
137
      }
138
    } else {
139
      // no user was found with that token
140
      throw new BadRequestHttpException("Wrong or expired change email token. If you aren't sure why this error occurs perhaps you've already confirmed your new email address. Please try logging in with it.");
141
    }
142
  }
143
144
  public function actionExport() {
145
    header("Content-Type: text/csv");
146
    header("Content-Disposition: attachment; filename=fsa-data-export-".Yii::$app->user->identity->email."-".date('Ymd').".csv");
0 ignored issues
show
Bug introduced by
Accessing email on the interface yii\web\IdentityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
147
148
    $reader = Yii::$app->user->identity->getExportData();
0 ignored issues
show
Bug introduced by
The method getExportData() does not exist on yii\web\IdentityInterface. It seems like you code against a sub-type of said class. However, the method does not exist in site\tests\_support\MockUser. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

148
    /** @scrutinizer ignore-call */ 
149
    $reader = Yii::$app->user->identity->getExportData();
Loading history...
149
    $fp = fopen('php://output', 'w');
150
151
    $header = [
152
      'Date',
153
      'Behavior',
154
      'Category',
155
      Question::$QUESTIONS[1],
156
      Question::$QUESTIONS[2],
157
      Question::$QUESTIONS[3],
158
    ];
159
160
    fputcsv($fp, $header);
161
    $user_behavior = Yii::$container->get(\common\interfaces\UserBehaviorInterface::class);
162
    while($row = $reader->read()) {
163
      $row = $user_behavior::decorate([$row]);
164
      $row = Yii::$app->user->identity->cleanExportRow($row[0]);
0 ignored issues
show
Bug introduced by
The method cleanExportRow() does not exist on yii\web\IdentityInterface. It seems like you code against a sub-type of said class. However, the method does not exist in site\tests\_support\MockUser. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

164
      /** @scrutinizer ignore-call */ 
165
      $row = Yii::$app->user->identity->cleanExportRow($row[0]);
Loading history...
165
      fputcsv($fp, $row);
166
    }
167
    fclose($fp);
168
169
    die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
170
  }
171
}
172