Passed
Push — v5 ( e348bf...8a8f01 )
by Alexey
06:35
created

UsersController   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 211
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 211
rs 8.3396
c 0
b 0
f 0
wmc 44

9 Methods

Rating   Name   Duplication   Size   Complexity  
A loginAction() 0 5 1
A cabinetAction() 0 13 2
A passreAction() 0 5 1
C fastRegistrationAction() 0 31 8
C getPartnerInfoAction() 0 48 9
A resendActivationAction() 0 14 3
C registrationAction() 0 29 8
A activationAction() 0 9 4
C attachEmailAction() 0 31 7

How to fix   Complexity   

Complex Class

Complex classes like UsersController 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 UsersController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Users app controller
5
 *
6
 * @author Alexey Krupskiy <[email protected]>
7
 * @link http://inji.ru/
8
 * @copyright 2015 Alexey Krupskiy
9
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
10
 */
11
class UsersController extends Controller {
0 ignored issues
show
Bug introduced by
The type Controller 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...
12
13
    public function indexAction() {
14
        Tools::redirect('/users/cabinet/profile');
0 ignored issues
show
Bug introduced by
The type Tools 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...
15
    }
16
17
    public function cabinetAction($activeSection = '') {
18
        $bread = [];
19
20
        $sections = $this->module->getSnippets('cabinetSection');
21
        if (!empty($sections[$activeSection]['name'])) {
22
            $this->view->setTitle($sections[$activeSection]['name'] . ' - ' . \I18n\Text::module('Users', 'Личный кабинет'));
23
            $bread[] = ['text' => 'Личный кабинет', 'href' => '/users/cabinet'];
24
            $bread[] = ['text' => $sections[$activeSection]['name']];
25
        } else {
26
            $this->view->setTitle('Личный кабинет');
27
            $bread[] = ['text' => 'Личный кабинет'];
28
        }
29
        $this->view->page(['data' => compact('widgets', 'sections', 'activeSection', 'bread')]);
30
    }
31
32
    public function loginAction() {
33
        $this->view->setTitle('Авторизация');
34
        $bread = [];
35
        $bread[] = ['text' => 'Авторизация'];
36
        $this->view->page(['data' => compact('bread')]);
37
    }
38
39
    public function passreAction() {
40
        $this->view->setTitle('Восстановление пароля');
41
        $bread = [];
42
        $bread[] = ['text' => 'Восстановление пароля'];
43
        $this->view->page(['data' => compact('bread')]);
44
    }
45
46
    public function registrationAction() {
47
        $this->view->setTitle('Регистрация');
48
        if (Users\User::$cur->user_id) {
49
            Tools::redirect('/', 'Вы уже зарегистрированы');
50
        }
51
        if (!empty($_POST)) {
52
            $error = false;
53
            if ($this->Recaptcha) {
54
                $response = $this->Recaptcha->check($_POST['g-recaptcha-response']);
55
                if ($response) {
56
                    if (!$response->success) {
57
                        Msg::add('Вы не прошли проверку на робота', 'danger');
0 ignored issues
show
Bug introduced by
The type Msg 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...
58
                        $error = true;
59
                    }
60
                } else {
61
                    Msg::add('Произошла ошибка, попробуйте ещё раз');
62
                    $error = true;
63
                }
64
            }
65
            if (!$error) {
66
                if ($this->Users->registration($_POST)) {
67
                    Tools::redirect('/');
68
                }
69
            }
70
        }
71
        $this->view->setTitle('Регистрация');
72
        $bread = [];
73
        $bread[] = ['text' => 'Регистрация'];
74
        $this->view->page(['data' => compact('bread')]);
75
    }
76
77
    public function fastRegistrationAction() {
78
        $result = new \Server\Result();
79
        if (Users\User::$cur->user_id) {
80
            $result->success = false;
81
            $result->content = 'Вы уже зарегистрированы';
82
            return $result->send();
83
        }
84
        if (!empty($_POST)) {
85
            $error = false;
86
            if ($this->Recaptcha) {
87
                $response = $this->Recaptcha->check($_POST['g-recaptcha-response']);
88
                if ($response) {
89
                    if (!$response->success) {
90
                        $result->success = false;
91
                        $result->content = 'Вы не прошли проверку на робота';
92
                        return $result->send();
93
                    }
94
                } else {
95
                    $result->success = false;
96
                    $result->content = 'Произошла ошибка, попробуйте ещё раз';
97
                    return $result->send();
98
                }
99
            }
100
            if (!$error) {
101
                $resultReg = $this->Users->registration($_POST, true, false);
102
                if (is_numeric($resultReg)) {
103
                    return $result->send();
104
                } else {
105
                    $result->success = false;
106
                    $result->content = $resultReg['error'];
107
                    return $result->send();
108
                }
109
110
            }
111
        }
112
    }
113
114
    public function activationAction($userId = 0, $hash = '') {
115
        $user = \Users\User::get((int) $userId);
116
        if (!$user || !$hash || $user->activation !== (string) $hash) {
117
            Tools::redirect('/', 'Во время активации произошли ошибки', 'danger');
118
        }
119
        $user->activation = '';
120
        $user->save();
121
        Inji::$inst->event('Users-completeActivation', $user);
122
        Tools::redirect('/', 'Вы успешно активировали ваш аккаунт', 'success');
123
    }
124
125
    public function attachEmailAction() {
126
        if (Users\User::$cur->mail) {
127
            Tools::redirect('/', 'К вашему аккаунту уже привязан E-Mail');
128
        }
129
        if (!empty($_POST['mail'])) {
130
            $user_mail = trim($_POST['mail']);
131
            if (!filter_var($user_mail, FILTER_VALIDATE_EMAIL)) {
132
                Msg::add('Вы ввели не корректный E-mail', 'danger');
133
            } else {
134
                $user = Users\User::get($user_mail, 'mail');
135
                if ($user && $user->id != Users\User::$cur->id) {
136
                    Msg::add('Данный E-mail уже привязан к другому аккаунту', 'danger');
137
                } else {
138
                    Users\User::$cur->mail = $user_mail;
139
                    if (!empty($this->module->config['needActivation'])) {
140
                        Users\User::$cur->activation = Tools::randomString();
141
                        $from = 'noreply@' . INJI_DOMAIN_NAME;
142
                        $to = $user_mail;
143
                        $subject = 'Активация аккаунта на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME);
144
                        $text = 'Для активации вашего аккаунта перейдите по ссылке <a href = "http://' . INJI_DOMAIN_NAME . '/users/activation/' . Users\User::$cur->id . '/' . Users\User::$cur->activation . '">http://' . idn_to_utf8(INJI_DOMAIN_NAME) . '/users/activation/' . Users\User::$cur->id . '/' . Users\User::$cur->activation . '</a>';
145
                        Tools::sendMail($from, $to, $subject, $text);
146
                        Msg::add('На указанный почтовый ящик была выслана ваша ссылка для подтверждения E-Mail', 'success');
147
                    } else {
148
                        Msg::add('Вы успешно привязали E-Mail к своему аккаунту', 'success');
149
                    }
150
                    Users\User::$cur->save();
151
                    Tools::redirect('/');
152
                }
153
            }
154
        }
155
        $this->view->page();
156
    }
157
158
    public function resendActivationAction($userId = 0) {
159
        $user = \Users\User::get((int) $userId);
160
        if (!$user) {
161
            Tools::redirect('/', 'Не указан пользователь', 'danger');
162
        }
163
        if (!$user->activation) {
164
            Tools::redirect('/', 'Пользователь уже активирован');
165
        }
166
        $from = 'noreply@' . INJI_DOMAIN_NAME;
167
        $to = $user->mail;
168
        $subject = 'Активация аккаунта на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME);
169
        $text = 'Для активации вашего аккаунта перейдите по ссылке <a href = "http://' . INJI_DOMAIN_NAME . '/users/activation/' . $user->id . '/' . $user->activation . '">http://' . idn_to_utf8(INJI_DOMAIN_NAME) . '/users/activation/' . $user->id . '/' . $user->activation . '</a>';
170
        Tools::sendMail($from, $to, $subject, $text);
171
        Tools::redirect('/', 'На указанный почтовый ящик была выслана ваша ссылка для подтверждения E-Mail', 'success');
172
    }
173
174
    public function getPartnerInfoAction($userId = 0) {
175
        $userId = (int) $userId;
176
        $result = new \Server\Result();
177
        if (!$userId) {
178
            $result->success = false;
179
            $result->content = 'Не указан пользователь';
180
            $result->send();
181
        }
182
        $partners = App::$cur->users->getUserPartners(Users\User::$cur, 8);
183
        if (empty($partners['users'][$userId])) {
184
            $result->success = false;
185
            $result->content = 'Этот пользователь не находится в вашей структуре';
186
            $result->send();
187
        }
188
        $user = $partners['users'][$userId];
189
        ob_start();
190
        echo "id:{$user->id}<br />";
191
        echo "E-mail: <a href='mailto:{$user->mail}'>{$user->mail}</a>";
192
        $rewards = Money\Reward::getList(['where' => ['active', 1]]);
193
        foreach ($rewards as $reward) {
194
            foreach ($reward->conditions as $condition) {
195
                $complete = $condition->checkComplete($userId);
196
                ?>
197
                <h5 class="<?= $complete ? 'text-success' : 'text-danger'; ?>"><?= $condition->name(); ?></h5>
198
                <ul>
199
                    <?php
200
                    foreach ($condition->items as $item) {
201
                        $itemComplete = $item->checkComplete($userId);
202
                        switch ($item->type) {
203
                            case 'event':
204
                                $name = \Events\Event::get($item->value, 'event')->name();
205
                                break;
206
                        }
207
                        ?>
208
                        <li>
209
                            <b class="<?= $itemComplete ? 'text-success' : 'text-danger'; ?>"><?= $name; ?> <?= $item->recivedCount($userId); ?></b>/<?= $item->count; ?>
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $name does not seem to be defined for all execution paths leading up to this point.
Loading history...
210
                            <br/>
211
                        </li>
212
                        <?php
213
                    }
214
                    ?>
215
                </ul>
216
                <?php
217
            }
218
        }
219
        $result->content = ob_get_contents();
220
        ob_end_clean();
221
        $result->send();
222
    }
223
224
}
225