Total Complexity | 40 |
Total Lines | 306 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like BaseController 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 BaseController, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
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(); |
||
|
|||
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; |
||
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 ); |
||
71 | if ( !$module ) { |
||
72 | $module = new PbxExtensionModules(); |
||
73 | $module->disabled = '1'; |
||
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 . ' | ' |
||
96 | . $this->translation->_( 'Breadcrumb' |
||
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'){ |
||
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 ) { |
||
148 | if ( $this->request->isAjax() === TRUE ) { |
||
149 | $this->view->disableLevel( [ |
||
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(); |
||
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 ); |
||
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( |
||
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{ |
||
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{ |
||
322 | } |
||
323 | } |
||
324 |