Total Complexity | 56 |
Total Lines | 326 |
Duplicated Lines | 0 % |
Changes | 4 | ||
Bugs | 0 | Features | 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 |
||
45 | class BaseController extends Controller |
||
46 | { |
||
47 | protected string $actionName; |
||
48 | protected string $controllerName; |
||
49 | protected string $controllerNameUnCamelized; |
||
50 | |||
51 | public const WIKI_LINKS = '/var/etc/wiki-links-LANG.json'; |
||
52 | |||
53 | /** |
||
54 | * Initializes base class |
||
55 | */ |
||
56 | public function initialize(): void |
||
66 | } |
||
67 | } |
||
68 | |||
69 | /** |
||
70 | * Кастомизация ссылок на wiki документацию для модулей. |
||
71 | * @param array $links |
||
72 | * @return void |
||
73 | */ |
||
74 | private function customModuleWikiLinks(array $links): void |
||
75 | { |
||
76 | $this->view->urlToWiki = $links[$this->language][$this->view->urlToWiki]??$this->view->urlToWiki; |
||
77 | $this->view->urlToSupport = $links[$this->language][$this->view->urlToSupport]??$this->view->urlToSupport; |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * Кастомизация ссылок на wiki документацию. |
||
82 | * @return void |
||
83 | */ |
||
84 | private function customWikiLinks(): void |
||
85 | { |
||
86 | if(!$this->session->get('auth')){ |
||
87 | return; |
||
88 | } |
||
89 | /** @var Redis $cache */ |
||
90 | $cache = $this->di->getShared(ModelsCacheProvider::SERVICE_NAME); |
||
91 | $links = $cache->get('WIKI_LINKS'); |
||
92 | |||
93 | if($links === null){ |
||
94 | $ttl = 86400; |
||
95 | $client = new GuzzleHttp\Client(); |
||
96 | $url = 'https://raw.githubusercontent.com/mikopbx/Core/master/src/Common/WikiLinks/'.$this->language.'.json'; |
||
97 | try { |
||
98 | $res = $client->request('GET', $url, ['timeout', 1]); |
||
99 | }catch (Exception $e){ |
||
100 | $res = null; |
||
101 | $ttl = 3600; |
||
102 | if($e->getCode() !== 404){ |
||
103 | Util::sysLogMsg('BaseController', 'Error access to raw.04githubusercontent.com'); |
||
104 | } |
||
105 | } |
||
106 | $links = null; |
||
107 | if($res && $res->getStatusCode() === 200){ |
||
108 | try { |
||
109 | $links = json_decode($res->getBody(), true, 512, JSON_THROW_ON_ERROR); |
||
110 | }catch (Exception $e){ |
||
111 | $ttl = 3600; |
||
112 | } |
||
113 | } |
||
114 | if(!is_array($links)){ |
||
115 | $links = []; |
||
116 | } |
||
117 | $cache->set('WIKI_LINKS', $links, $ttl); |
||
118 | } |
||
119 | |||
120 | $filename = str_replace('LANG', $this->language, self::WIKI_LINKS); |
||
121 | if(file_exists($filename)){ |
||
122 | try { |
||
123 | $local_links = json_decode(file_get_contents($filename), true, 512, JSON_THROW_ON_ERROR); |
||
124 | $links = $local_links; |
||
125 | }catch (\Exception $e){ |
||
126 | Util::sysLogMsg('BaseController', $e->getMessage()); |
||
127 | } |
||
128 | } |
||
129 | $this->view->urlToWiki = $links[$this->view->urlToWiki]??$this->view->urlToWiki; |
||
130 | $this->view->urlToSupport = $links[$this->view->urlToSupport]??$this->view->urlToSupport; |
||
131 | } |
||
132 | |||
133 | /** |
||
134 | * Prepares some environments to every controller and view |
||
135 | * |
||
136 | */ |
||
137 | protected function prepareView(): void |
||
138 | { |
||
139 | date_default_timezone_set($this->getSessionData('PBXTimezone')); |
||
140 | $roSession = $this->sessionRO; |
||
141 | $this->view->PBXVersion = $this->getSessionData('PBXVersion'); |
||
142 | if ($roSession !== null && array_key_exists('auth', $roSession)) { |
||
143 | $this->view->SSHPort = $this->getSessionData('SSHPort'); |
||
144 | $this->view->PBXLicense = $this->getSessionData('PBXLicense'); |
||
145 | } else { |
||
146 | $this->view->SSHPort = ''; |
||
147 | $this->view->PBXLicense = ''; |
||
148 | } |
||
149 | // Кеш версий модулей и атс, для правильной работы АТС при установке модулей |
||
150 | $versionHash = $this->getVersionsHash(); |
||
151 | $this->session->set('versionHash', $versionHash); |
||
152 | |||
153 | $this->view->WebAdminLanguage = $this->getSessionData('WebAdminLanguage'); |
||
154 | $this->view->AvailableLanguages = json_encode($this->elements->getAvailableWebAdminLanguages()); |
||
155 | |||
156 | if ($roSession !== null && array_key_exists('SubmitMode', $roSession)) { |
||
157 | $this->view->submitMode = $roSession['SubmitMode']; |
||
158 | } else { |
||
159 | $this->view->submitMode = 'SaveSettings'; |
||
160 | } |
||
161 | |||
162 | // Добавим версию модуля, если это модуль |
||
163 | $moduleLinks = []; |
||
164 | if ($this->moduleName === 'PBXExtension') { |
||
165 | /** @var PbxExtensionModules $module */ |
||
166 | $module = PbxExtensionModules::findFirstByUniqid($this->controllerName); |
||
167 | if ($module === null) { |
||
168 | $module = new PbxExtensionModules(); |
||
169 | $module->disabled = '1'; |
||
170 | $module->name = 'Unknown module'; |
||
171 | }else{ |
||
172 | try { |
||
173 | $links = json_decode($module->wiki_links, true, 512, JSON_THROW_ON_ERROR); |
||
|
|||
174 | if(is_array($links)){ |
||
175 | $moduleLinks = $links; |
||
176 | } |
||
177 | }catch (\JsonException $e){ |
||
178 | Util::sysLogMsg(__CLASS__, $e->getMessage()); |
||
179 | } |
||
180 | } |
||
181 | $this->view->module = $module; |
||
182 | } |
||
183 | |||
184 | // Разрешим отправку анонимной информации об ошибках |
||
185 | if ($this->getSessionData('SendMetrics') === '1') { |
||
186 | touch('/tmp/sendmetrics'); |
||
187 | $this->view->lastSentryEventId = SentrySdk::getCurrentHub()->getLastEventId(); |
||
188 | } else { |
||
189 | if (file_exists('/tmp/sendmetrics')) { |
||
190 | unlink('/tmp/sendmetrics'); |
||
191 | } |
||
192 | $this->view->lastSentryEventId = null; |
||
193 | } |
||
194 | $title = 'MikoPBX'; |
||
195 | switch ($this->actionName) { |
||
196 | case'index': |
||
197 | case'delete': |
||
198 | case'save': |
||
199 | case'modify': |
||
200 | case'*** WITHOUT ACTION ***': |
||
201 | $title .= '|'. $this->translation->_("Breadcrumb{$this->controllerName}"); |
||
202 | break; |
||
203 | default: |
||
204 | $title .= '|'. $this->translation->_("Breadcrumb{$this->controllerName}{$this->actionName}"); |
||
205 | } |
||
206 | Tag::setTitle($title); |
||
207 | $this->view->t = $this->translation; |
||
208 | $this->view->debugMode = $this->config->path('adminApplication.debugMode'); |
||
209 | $this->view->urlToLogo = $this->url->get('assets/img/logo-mikopbx.svg'); |
||
210 | if ($this->language === 'ru') { |
||
211 | $this->view->urlToWiki = "https://wiki.mikopbx.com/{$this->controllerNameUnCamelized}"; |
||
212 | $this->view->urlToSupport = 'https://www.mikopbx.ru/support/?fromPBX=true'; |
||
213 | } else { |
||
214 | $this->view->urlToWiki = "https://wiki.mikopbx.com/{$this->language}:{$this->controllerNameUnCamelized}"; |
||
215 | $this->view->urlToSupport = 'https://www.mikopbx.com/support/?fromPBX=true'; |
||
216 | } |
||
217 | $this->view->urlToController = $this->url->get($this->controllerNameUnCamelized); |
||
218 | $this->view->represent = ''; |
||
219 | $this->view->cacheName = "{$this->controllerName}{$this->actionName}{$this->language}{$versionHash}"; |
||
220 | |||
221 | // If it is module we have to use another template |
||
222 | if ($this->moduleName === 'PBXExtension') { |
||
223 | $this->customModuleWikiLinks($moduleLinks); |
||
224 | $this->view->setTemplateAfter('modules'); |
||
225 | } else { |
||
226 | $this->customWikiLinks(); |
||
227 | $this->view->setTemplateAfter('main'); |
||
228 | } |
||
229 | } |
||
230 | |||
231 | /** |
||
232 | * Gets data from session or database if it not exists in session store |
||
233 | * |
||
234 | * @param $key string session parameter |
||
235 | * |
||
236 | * @return string |
||
237 | */ |
||
238 | protected function getSessionData(string $key): string |
||
239 | { |
||
240 | $roSession = $this->sessionRO; |
||
241 | if ($roSession !== null && array_key_exists($key, $roSession) && ! empty($roSession[$key])) { |
||
242 | $value = $roSession[$key]; |
||
243 | } else { |
||
244 | $value = PbxSettings::getValueByKey($key); |
||
245 | $this->session->set($key, $value); |
||
246 | } |
||
247 | |||
248 | return $value; |
||
249 | } |
||
250 | |||
251 | /** |
||
252 | * Generates common hash sum for correct combine CSS and JS according to installed modules |
||
253 | * |
||
254 | */ |
||
255 | private function getVersionsHash(): string |
||
256 | { |
||
257 | $result = PbxSettings::getValueByKey('PBXVersion'); |
||
258 | $modulesVersions = PbxExtensionModules::getModulesArray(); |
||
259 | foreach ($modulesVersions as $module) { |
||
260 | $result .= "{$module['id']}{$module['version']}"; |
||
261 | } |
||
262 | |||
263 | return md5($result); |
||
264 | } |
||
265 | |||
266 | /** |
||
267 | * Changes the AJAX response by expected format |
||
268 | * |
||
269 | * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface |
||
270 | */ |
||
271 | public function afterExecuteRoute() |
||
299 | } |
||
300 | |||
301 | /** |
||
302 | * Callback before execute any route |
||
303 | */ |
||
304 | public function beforeExecuteRoute(): void |
||
310 | } |
||
311 | } |
||
312 | } |
||
313 | |||
314 | /** |
||
315 | * Change page without reload browser page |
||
316 | * |
||
317 | * @param string $uri |
||
318 | */ |
||
319 | protected function forward(string $uri): void |
||
320 | { |
||
321 | $uriParts = explode('/', $uri); |
||
322 | $params = array_slice($uriParts, 2); |
||
323 | |||
324 | $this->dispatcher->forward( |
||
325 | [ |
||
326 | 'controller' => $uriParts[0], |
||
327 | 'action' => $uriParts[1], |
||
328 | 'params' => $params, |
||
329 | ] |
||
330 | |||
331 | ); |
||
332 | } |
||
333 | |||
334 | /** |
||
335 | * Removes all dangerous symbols from CallerID |
||
336 | * @param string $callerId |
||
337 | * |
||
338 | * @return string |
||
339 | */ |
||
340 | protected function sanitizeCallerId(string $callerId): string |
||
343 | } |
||
344 | |||
345 | /** |
||
346 | * Sorts array by priority field |
||
347 | * |
||
348 | * @param $a |
||
349 | * @param $b |
||
350 | * |
||
351 | * @return int|null |
||
352 | */ |
||
353 | protected function sortArrayByPriority($a, $b): ?int |
||
371 | } |
||
372 | } |
||
373 | } |
||
374 |