Passed
Push — master ( 90372d...e80252 )
by Nikolay
25:24
created

BaseController::forward()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 9
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 1
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, 6 2018
7
 *
8
 */
9
10
use Models\PbxExtensionModules;
11
use Phalcon\Mvc\Controller;
12
use Phalcon\Mvc\Dispatcher;
13
use Phalcon\Mvc\View;
14
use Phalcon\Text;
15
16
class BaseController extends Controller {
17
18
    protected $di;
19
    protected $actionName;
20
    protected $controllerName;
21
    protected $controllerNameUnCamelized;
22
23
24
    /**
25
     * Инициализация базововго класса
26
     */
27
    public function initialize(){
28
        $this->di                    = $this->getDi();
29
        $this->actionName            = $this->dispatcher->getActionName();
30
        $this->controllerName        = Text::camelize($this->dispatcher->getControllerName(),'_');
31
        $this->controllerNameUnCamelized = Text::uncamelize( $this->controllerName  ,'-');
32
33
        $this->moduleName            = $this->dispatcher->getModuleName();
0 ignored issues
show
Bug Best Practice introduced by
The property moduleName does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
34
35
        if ( $this->request->isAjax() === FALSE ) {
36
            $this->prepareView( );
37
        }
38
    }
39
40
41
    /**
42
     * Инициализирует шаблонизатор View и устанавливает переменные системы для отображения
43
     */
44
    protected function prepareView() :void{
45
        date_default_timezone_set( $this->getSessionData('PBXTimezone') );
46
        $roSession  = $this->sessionRO;
0 ignored issues
show
Bug Best Practice introduced by
The property sessionRO does not exist on BaseController. Since you implemented __get, consider adding a @property annotation.
Loading history...
47
        $this->view->PBXVersion = $this->getSessionData('PBXVersion');
48
        if ( $roSession !== null && array_key_exists('auth', $roSession)) {
49
            $this->view->SSHPort    = $this->getSessionData('SSHPort');
50
            $this->view->PBXLicense = $this->getSessionData('PBXLicense');
51
            $this->view->PBXLanguage= $this->getSessionData('PBXLanguage');
52
        } else {
53
            $this->view->SSHPort    = '';
54
            $this->view->PBXLicense = '';
55
            $this->view->PBXLanguage= '';
56
        }
57
58
        // Кеш версий модулей и атс, для правильной работы АТС при установке модулей
59
        $versionHash = $this->getVersionsHash();
60
        $this->session->set( 'versionHash', $versionHash);
61
62
        if ( $roSession !== null && array_key_exists('SubmitMode', $roSession)) {
63
            $this->view->submitMode = $roSession[ 'SubmitMode' ];
64
        } else {
65
            $this->view->submitMode = 'SaveSettings';
66
        }
67
68
        // Добавим версию модуля, если это модуль
69
        if ( $this->moduleName === 'PBXExtension' ) {
70
            $module = PbxExtensionModules::findFirstByUniqid( $this->controllerName );
0 ignored issues
show
Bug introduced by
The method findFirstByUniqid() does not exist on Models\PbxExtensionModules. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

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

70
            /** @scrutinizer ignore-call */ 
71
            $module = PbxExtensionModules::findFirstByUniqid( $this->controllerName );
Loading history...
71
            if ( !$module ) {
72
                $module = new PbxExtensionModules();
73
                $module->disabled = '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 $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...
74
                $module->name = 'Unknown module';
75
            }
76
            $this->view->module = $module;
77
        }
78
79
        // Разрешим отправку анонимной информации об ошибках
80
        if ($this->getSessionData('SendMetrics') === '1'){
81
            touch('/tmp/sendmetrics');
82
            $this->view->lastSentryEventId = Sentry\State\Hub::getCurrent()->getLastEventId();
83
        } else {
84
            if (file_exists('/tmp/sendmetrics')){
85
                unlink('/tmp/sendmetrics');
86
            }
87
            $this->view->lastSentryEventId = Null;
88
        }
89
        switch ( $this->actionName ) {
90
            case'index':
91
            case'delete':
92
            case'save':
93
            case'modify':
94
            case'*** WITHOUT ACTION ***':
95
                $this->tag->setTitle( $this->config->application->kind . ' | '
0 ignored issues
show
Bug Best Practice introduced by
The property config does not exist on BaseController. Since you implemented __get, consider adding a @property annotation.
Loading history...
96
                    . $this->translation->_( 'Breadcrumb'
0 ignored issues
show
Bug Best Practice introduced by
The property translation does not exist on BaseController. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
The method _() 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

96
                    . $this->translation->/** @scrutinizer ignore-call */ _( 'Breadcrumb'

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...
97
                        . $this->controllerName ) );
98
                break;
99
            default:
100
                $this->tag->setTitle( $this->config->application->kind . ' | '
101
                    . $this->translation->_( 'Breadcrumb'
102
                        . $this->controllerName
103
                        . $this->actionName ) );
104
        }
105
106
        $this->view->t = $this->translation;
107
        $this->view->debugMode = $this->config->application->debugMode;
108
        $this->view->urlToLogo = $this->url->get( 'public/img/logo-mikopbx.svg' );
109
        if ($this->language === 'ru'){
0 ignored issues
show
Bug Best Practice introduced by
The property language does not exist on BaseController. Since you implemented __get, consider adding a @property annotation.
Loading history...
110
            $this->view->urlToWiki
111
                = "https://wiki.mikopbx.com/{$this->controllerNameUnCamelized}";
112
        } else {
113
            $this->view->urlToWiki
114
                = "https://wiki.mikopbx.com/{$this->language}:{$this->controllerNameUnCamelized}";
115
        }
116
117
        $this->view->urlToController = $this->url->get( $this->controllerNameUnCamelized );
118
        $this->view->represent       = '';
119
        $this->view->cacheName       = "{$this->controllerName}{$this->actionName}{$this->language}{$versionHash}";
120
121
        // Подключим нужный View
122
        if ( $this->moduleName  === 'PBXExtension' ) {
123
            $this->view->setTemplateAfter( 'modules' );
124
        } else {
125
            $this->view->setTemplateAfter( 'main' );
126
        }
127
128
        // Для модулей кинем в кеш все статические картинки
129
        if ( $this->moduleName  === 'PBXExtension' ) {
130
            $modulesDir = $this->getDI()->getModulesDir();
131
            $moduleImageDir = $modulesDir . $this->controllerName.'/public/img';
132
            $moduleImageCacheDir = $this->config->application->imgCacheDir.$this->controllerName;
133
            if (file_exists($moduleImageDir)
134
                && !file_exists($moduleImageCacheDir)){
135
                symlink ( $moduleImageDir, $moduleImageCacheDir );
136
            }
137
        }
138
    }
139
140
    /**
141
     * Постобработка запроса
142
     *
143
     * @param \Phalcon\Mvc\Dispatcher $dispatcher
144
     *
145
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
146
     */
147
    public function afterExecuteRoute( Dispatcher $dispatcher ) {
0 ignored issues
show
Unused Code introduced by
The parameter $dispatcher is not used and could be removed. ( Ignorable by Annotation )

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

147
    public function afterExecuteRoute( /** @scrutinizer ignore-unused */ Dispatcher $dispatcher ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
148
        if ( $this->request->isAjax() === TRUE ) {
149
            $this->view->disableLevel( [
0 ignored issues
show
Bug introduced by
The method disableLevel() does not exist on Phalcon\Mvc\ViewInterface. Did you maybe mean disable()? ( Ignorable by Annotation )

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

149
            $this->view->/** @scrutinizer ignore-call */ 
150
                         disableLevel( [

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...
150
                View::LEVEL_ACTION_VIEW     => TRUE,
151
                View::LEVEL_LAYOUT          => TRUE,
152
                View::LEVEL_MAIN_LAYOUT     => TRUE,
153
                View::LEVEL_AFTER_TEMPLATE  => TRUE,
154
                View::LEVEL_BEFORE_TEMPLATE => TRUE,
155
            ] );
156
            $this->response->setContentType( 'application/json', 'UTF-8' );
157
            $data = $this->view->getParamsToView();
158
159
            /* Set global params if is not set in controller/action */
160
            if (is_array($data) && isset($data['raw_response'])){
161
                $result = $data['raw_response'];
162
            } elseif ( is_array( $data ) ) {
163
                $data['success'] = array_key_exists( 'success', $data ) ? $data['success'] : TRUE;
164
                $data['reload']  = array_key_exists( 'reload', $data ) ? $data['reload'] : FALSE;
165
                $data['message'] = $data['message'] ?? $this->flash->getMessages();
0 ignored issues
show
Bug introduced by
The method getMessages() does not exist on Phalcon\Flash\Direct. ( Ignorable by Annotation )

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

165
                $data['message'] = $data['message'] ?? $this->flash->/** @scrutinizer ignore-call */ getMessages();

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...
166
167
                // Добавим информацию о последней ошибке для отображения диалогового окна для пользователя
168
                if (file_exists('/tmp/sendmetrics')) {
169
                    $data['lastSentryEventId'] = Sentry\State\Hub::getCurrent()->getLastEventId();
170
                }
171
                $result            = json_encode( $data );
172
            }
173
174
            $this->response->setContent( $result );
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.
Loading history...
175
        }
176
        return $this->response->send();
177
    }
178
179
    /**
180
     * Перехват события перед обработкой в контроллере
181
     */
182
    public function beforeExecuteRoute() :void{
183
        if ($this->request->isPost()){
184
            $data = $this->request->getPost('submitMode');
185
            if (!empty($data)){
186
                $this->session->set('SubmitMode', $data);
187
            }
188
        }
189
    }
190
191
    /**
192
     * Перевод страниц без перезагрузки страниц
193
     *
194
     * @param string $uri
195
     */
196
    protected function forward( $uri ) {
197
        $uriParts = explode( '/', $uri );
198
        $params   = array_slice( $uriParts, 2 );
199
200
        return $this->dispatcher->forward(
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->dispatcher->forwa..., 'params' => $params)) targeting Phalcon\Dispatcher\DispatcherInterface::forward() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
Are you sure the usage of $this->dispatcher->forwa..., 'params' => $params)) targeting Phalcon\Mvc\Dispatcher::forward() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
201
            [
202
                'controller' => $uriParts[0],
203
                'action'     => $uriParts[1],
204
                'params'     => $params,
205
            ]
206
207
        );
208
    }
209
210
    /**
211
     * Транслитерация переданной строки
212
     *
213
     * @param $string
214
     *
215
     * @return string
216
     */
217
    protected function transliterate( $string ) :string{
218
219
        $converter = [
220
            'а' => 'a',
221
            'б' => 'b',
222
            'в' => 'v',
223
            'г' => 'g',
224
            'д' => 'd',
225
            'е' => 'e',
226
            'ё' => 'e',
227
            'ж' => 'zh',
228
            'з' => 'z',
229
            'и' => 'i',
230
            'й' => 'y',
231
            'к' => 'k',
232
            'л' => 'l',
233
            'м' => 'm',
234
            'н' => 'n',
235
            'о' => 'o',
236
            'п' => 'p',
237
            'р' => 'r',
238
            'с' => 's',
239
            'т' => 't',
240
            'у' => 'u',
241
            'ф' => 'f',
242
            'х' => 'h',
243
            'ц' => 'c',
244
            'ч' => 'ch',
245
            'ш' => 'sh',
246
            'щ' => 'sch',
247
            'ь' => 'i',
248
            'ы' => 'y',
249
            'ъ' => '',
250
            'э' => 'e',
251
            'ю' => 'yu',
252
            'я' => 'ya',
253
254
            'А' => 'A',
255
            'Б' => 'B',
256
            'В' => 'V',
257
            'Г' => 'G',
258
            'Д' => 'D',
259
            'Е' => 'E',
260
            'Ё' => 'E',
261
            'Ж' => 'Zh',
262
            'З' => 'Z',
263
            'И' => 'I',
264
            'Й' => 'Y',
265
            'К' => 'K',
266
            'Л' => 'L',
267
            'М' => 'M',
268
            'Н' => 'N',
269
            'О' => 'O',
270
            'П' => 'P',
271
            'Р' => 'R',
272
            'С' => 'S',
273
            'Т' => 'T',
274
            'У' => 'U',
275
            'Ф' => 'F',
276
            'Х' => 'H',
277
            'Ц' => 'C',
278
            'Ч' => 'Ch',
279
            'Ш' => 'Sh',
280
            'Щ' => 'Sch',
281
            'Ь' => 'I',
282
            'Ы' => 'Y',
283
            'Ъ' => ' ',
284
            'Э' => 'E',
285
            'Ю' => 'Yu',
286
            'Я' => 'Ya',
287
        ];
288
289
        return strtr( $string, $converter );
290
291
    }
292
293
    /**
294
     * Генерирует хеш из версий установленных модулей и АТС, для корректного склеивания JS, CSS и локализаций.
295
     *
296
     */
297
    private function getVersionsHash() :string{
298
        $result = Models\PbxSettings::getValueByKey( 'PBXVersion' );
299
        $modulesVersions = Models\PbxExtensionModules::find(['columns'=>'id,version']);
300
        foreach ($modulesVersions as $module) {
301
            $result.="{$module->version}{$module->version}";
302
        }
303
        return md5($result);
304
    }
305
306
    /**
307
     * Берет данные из сессии или из базы данных и записывает в кеш
308
     *
309
     * @param $key string параметры сессии
310
     *
311
     * @return string
312
     */
313
    protected function getSessionData($key) :string{
314
        $roSession  = $this->sessionRO;
0 ignored issues
show
Bug Best Practice introduced by
The property sessionRO does not exist on BaseController. Since you implemented __get, consider adding a @property annotation.
Loading history...
315
        if ( $roSession !== null && array_key_exists($key, $roSession) && !empty($roSession[ $key ])) {
316
            $value = $roSession[ $key ];
317
        } else {
318
            $value = Models\PbxSettings::getValueByKey( $key ) ;
319
            $this->session->set( $key, $value);
320
        }
321
        return $value;
322
    }
323
}
324