Passed
Push — develop ( 89a15e...42508e )
by Nikolay
05:59 queued 11s
created

ProvidersController   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 302
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 50
eloc 160
dl 0
loc 302
rs 8.4
c 1
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A indexAction() 0 19 4
A modifyiaxAction() 0 19 2
A saveAction() 0 31 5
F saveProvider() 0 73 19
B deleteAction() 0 30 8
A modifysipAction() 0 21 2
A enableAction() 0 21 5
A disableAction() 0 21 5

How to fix   Complexity   

Complex Class

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

1
<?php
2
/**
3
 * Copyright (C) MIKO LLC - All Rights Reserved
4
 * Unauthorized copying of this file, via any medium is strictly prohibited
5
 * Proprietary and confidential
6
 * Written by Nikolay Beketov, 5 2018
7
 *
8
 */
9
10
namespace MikoPBX\AdminCabinet\Controllers;
11
12
use MikoPBX\AdminCabinet\Forms\{IaxProviderEditForm, SipProviderEditForm};
13
use MikoPBX\Common\Models\{Iax, Providers, Sip};
14
15
class ProvidersController extends BaseController
16
{
17
18
    /**
19
     * Получение общего списка провайдеров
20
     */
21
    public function indexAction(): void
22
    {
23
        $providers     = Providers::find();
24
        $providersList = [];
25
        foreach ($providers as $provider) {
26
            $modelType       = ucfirst($provider->type);
27
            $provByType      = $provider->$modelType;
28
            $providersList[] = [
29
                'uniqid'     => $provByType->uniqid,
30
                'name'       => $provByType->description,
31
                'username'   => $provByType->username,
32
                'hostname'   => $provByType->host,
33
                'type'       => $provider->type,
34
                'status'     => $provByType->disabled ? 'disabled' : '',
35
                'existLinks' => $provider->OutgoingRouting->count() > 0 ? 'true' : 'false',
36
37
            ];
38
        }
39
        $this->view->providerlist = $providersList;
40
    }
41
42
43
    /**
44
     * Открытие карточки SIP провайдера и заполнение значений по умолчанию
45
     *
46
     * @param string $uniqid Уникальный идентификатор провайдера, если мы открываем существующего
47
     */
48
    public function modifysipAction($uniqid = null): void
49
    {
50
        $provider = Providers::findFirstByUniqid($uniqid);
51
52
        if ($provider === null) {
53
            $uniqid                     = strtoupper('SIP-' . time());
54
            $provider                   = new Providers();
55
            $provider->type             = 'SIP';
56
            $provider->uniqid           = $uniqid;
57
            $provider->sipuid           = $uniqid;
58
            $provider->Sip              = new Sip();
0 ignored issues
show
Bug Best Practice introduced by
The property Sip does not exist on MikoPBX\Common\Models\Providers. Since you implemented __set, consider adding a @property annotation.
Loading history...
59
            $provider->Sip->uniqid      = $uniqid;
0 ignored issues
show
Bug Best Practice introduced by
The property Sip does not exist on MikoPBX\Common\Models\Providers. Since you implemented __get, consider adding a @property annotation.
Loading history...
60
            $provider->Sip->type        = 'friend';
61
            $provider->Sip->port        = 5060;
62
            $provider->Sip->disabled    = '0';
0 ignored issues
show
Documentation Bug introduced by
It seems like '0' of type string is incompatible with the declared type integer|null of property $disabled.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
63
            $provider->Sip->qualifyfreq = 60;
64
            $provider->Sip->qualify     = '1';
0 ignored issues
show
Documentation Bug introduced by
It seems like '1' of type string is incompatible with the declared type integer|null of property $qualify.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
65
        }
66
67
        $this->view->form      = new SipProviderEditForm($provider->Sip);
68
        $this->view->represent = $provider->getRepresent();
69
    }
70
71
    /**
72
     * Открытие карточки IAX провайдера и заполнение значений по умолчанию
73
     *
74
     * @param string $uniqid Уникальный идентификатор провайдера, если мы открываем существующего
75
     */
76
    public function modifyiaxAction($uniqid = null): void
77
    {
78
79
        $provider = Providers::findFirstByUniqid($uniqid);
80
81
        if ($provider === null) {
82
            $uniqid                    = strtoupper('IAX-' . time());
83
            $provider                  = new Providers();
84
            $provider->type            = 'IAX';
85
            $provider->uniqid          = $uniqid;
86
            $provider->iaxuid          = $uniqid;
87
            $provider->Iax             = new Iax();
0 ignored issues
show
Bug Best Practice introduced by
The property Iax does not exist on MikoPBX\Common\Models\Providers. Since you implemented __set, consider adding a @property annotation.
Loading history...
88
            $provider->Iax->uniqid     = $uniqid;
0 ignored issues
show
Bug Best Practice introduced by
The property Iax does not exist on MikoPBX\Common\Models\Providers. Since you implemented __get, consider adding a @property annotation.
Loading history...
89
            $provider->Iax->disabled   = '0';
0 ignored issues
show
Documentation Bug introduced by
It seems like '0' of type string is incompatible with the declared type integer|null of property $disabled.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
90
            $provider->Iax->qualify    = '1';
0 ignored issues
show
Documentation Bug introduced by
It seems like '1' of type string is incompatible with the declared type integer|null of property $qualify.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
91
        }
92
93
        $this->view->form      = new IaxProviderEditForm($provider->Iax);
94
        $this->view->represent = $provider->getRepresent();
95
    }
96
97
    /**
98
     * Включение провайдера
99
     *
100
     * @param string $type   тип провайдера SIP или IAX
101
     * @param string $uniqid Уникальный идентификатор провайдера, если мы открываем существующего
102
     */
103
    public function enableAction($type, $uniqid = null): void
104
    {
105
        $this->view->success = false;
106
        switch ($type) {
107
            case 'iax':
108
            {
109
                $provider = Iax::findFirstByUniqid($uniqid);
110
                break;
111
            }
112
            case 'sip':
113
            {
114
                $provider = Sip::findFirstByUniqid($uniqid);
115
                break;
116
            }
117
            default:
118
                $provider = null;
119
        }
120
        if ($provider !== null) {
121
            $provider->disabled = '0';
122
            if ($provider->save() === true) {
123
                $this->view->success = true;
124
            }
125
        }
126
    }
127
128
    /**
129
     * Отключение провайдера
130
     *
131
     * @param string $type   тип провайдера SIP или IAX
132
     * @param string $uniqid Уникальный идентификатор провайдера, если мы открываем существующего
133
     */
134
    public function disableAction($type, $uniqid = null): void
135
    {
136
        $this->view->success = false;
137
        switch ($type) {
138
            case 'iax':
139
            {
140
                $provider = Iax::findFirstByUniqid($uniqid);
141
                break;
142
            }
143
            case 'sip':
144
            {
145
                $provider = Sip::findFirstByUniqid($uniqid);
146
                break;
147
            }
148
            default:
149
                $provider = null;
150
        }
151
        if ($provider !== null) {
152
            $provider->disabled = '1';
153
            if ($provider->save() === true) {
154
                $this->view->success = true;
155
            }
156
        }
157
    }
158
159
    /**
160
     * Сохранение провайдера AJAX запросом из формы
161
     *
162
     * @param bool $type - sip или iax
163
     *
164
     */
165
    public function saveAction($type): void
166
    {
167
        if ( ! $this->request->isPost()) {
168
            $this->forward('network/index');
169
        }
170
        $this->db->begin();
171
        $data = $this->request->getPost();
172
173
        // Заполним параметры провайдера и его SIP IAX записей
174
        if ( ! $this->saveProvider($data, $type)) {
175
            $this->view->success = false;
176
            $this->db->rollback();
177
178
            return;
179
        }
180
181
        // Заполним параметры Кодеков
182
        if ( ! $this->saveCodecs($data, $type)) {
0 ignored issues
show
Bug introduced by
The method saveCodecs() does not exist on MikoPBX\AdminCabinet\Con...ers\ProvidersController. ( Ignorable by Annotation )

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

182
        if ( ! $this->/** @scrutinizer ignore-call */ saveCodecs($data, $type)) {

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...
183
            $this->view->success = false;
184
            $this->db->rollback();
185
186
            return;
187
        }
188
189
        $this->flash->success($this->translation->_('ms_SuccessfulSaved'));
190
        $this->view->success = true;
191
        $this->db->commit();
192
193
        // Если это было создание карточки то надо перегрузить страницу с указанием ID
194
        if (empty($data['id'])) {
195
            $this->view->reload = "providers/modify{$type}/{$data['uniqid']}";
196
        }
197
    }
198
199
    /**
200
     * Сохранение параметров в таблицу  Providers
201
     *
202
     * @param array $data - POST дата
203
     * @param bool  $type - sip или iax
204
     *
205
     * @return bool результат сохранения
206
     */
207
    private function saveProvider($data, $type): bool
208
    {
209
        // Проверим это новый провайдер или старый
210
        $provider = Providers::findFirstByUniqid($data['uniqid']);
211
        if ($provider === null) {
212
            $provider         = new Providers();
213
            $provider->uniqid = $data['uniqid'];
214
            switch ($type) {
215
                case 'iax':
216
                    $provider->iaxuid = $data['uniqid'];
217
                    $provider->type   = 'IAX';
218
                    $provider->Iax    = new Iax();
0 ignored issues
show
Bug Best Practice introduced by
The property Iax does not exist on MikoPBX\Common\Models\Providers. Since you implemented __set, consider adding a @property annotation.
Loading history...
219
                    break;
220
                case 'sip':
221
                    $provider->sipuid = $data['uniqid'];
222
                    $provider->type   = 'SIP';
223
                    $provider->Sip    = new Sip();
0 ignored issues
show
Bug Best Practice introduced by
The property Sip does not exist on MikoPBX\Common\Models\Providers. Since you implemented __set, consider adding a @property annotation.
Loading history...
224
                    break;
225
            }
226
        }
227
228
        if ($provider->save() === false) {
229
            $errors = $provider->getMessages();
230
            $this->flash->warning(implode('<br>', $errors));
231
232
            return false;
233
        }
234
235
        switch ($type) {
236
            case 'iax':
237
                $providerByType = $provider->Iax;
0 ignored issues
show
Bug Best Practice introduced by
The property Iax does not exist on MikoPBX\Common\Models\Providers. Since you implemented __get, consider adding a @property annotation.
Loading history...
238
                break;
239
            case 'sip':
240
                $providerByType = $provider->Sip;
0 ignored issues
show
Bug Best Practice introduced by
The property Sip does not exist on MikoPBX\Common\Models\Providers. Since you implemented __get, consider adding a @property annotation.
Loading history...
241
                break;
242
            default:
243
                $providerByType = [];
244
        }
245
246
        foreach ($providerByType as $name => $value) {
247
            switch ($name) {
248
                case 'id':
249
                    break;
250
                case 'qualify':
251
                case 'disablefromuser':
252
                case 'noregister':
253
                case 'receive_calls_without_auth':
254
                    if (array_key_exists($name, $data)) {
255
                        $providerByType->$name = ($data[$name] === 'on') ? 1 : 0;
256
                    } else {
257
                        $providerByType->$name = 0;
258
                    }
259
                    break;
260
                case 'manualattributes':
261
                    if (array_key_exists($name, $data)) {
262
                        $providerByType->setManualAttributes($data[$name]);
263
                    }
264
                    break;
265
                default:
266
                    if (array_key_exists($name, $data)) {
267
                        $providerByType->$name = $data[$name];
268
                    }
269
            }
270
        }
271
272
        if ($providerByType->save() === false) {
273
            $errors = $providerByType->getMessages();
274
            $this->flash->warning(implode('<br>', $errors));
275
276
            return false;
277
        }
278
279
        return true;
280
    }
281
282
    /**
283
     * Удаление провайдера
284
     *
285
     * @param string $uniqid Уникальный идентификатор провайдера
286
     */
287
    public function deleteAction($uniqid = null): void
288
    {
289
        $provider = Providers::findFirstByUniqid($uniqid);
290
291
        if ($provider !== null) {
292
            $this->db->begin();
293
            $errors = null;
294
            if ($provider->Iax) {
295
                $iax = $provider->Iax;
296
                if ( ! $iax->delete()) {
297
                    $errors = $iax->getMessages();
298
                }
299
            }
300
301
            if ($errors === false && $provider->Sip) {
302
                $sip = $provider->Sip;
303
                if ( ! $sip->delete()) {
304
                    $errors = $sip->getMessages();
305
                }
306
            }
307
308
            if ($errors) {
309
                $this->flash->warning(implode('<br>', $errors));
310
                $this->db->rollback();
311
            } else {
312
                $this->db->commit();
313
            }
314
        }
315
316
        $this->forward('providers/index');
317
    }
318
319
}