Passed
Pull Request — developer (#334)
by Arkadiusz
42:56 queued 07:57
created

View::getFooterScripts()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 55
rs 8.9818
c 0
b 0
f 0
cc 3
nc 4
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Controller class for views.
4
 *
5
 * @package Controller
6
 *
7
 * @copyright YetiForce Sp. z o.o.
8
 * @license   YetiForce Public License 3.0 (licenses/LicenseEN.txt or yetiforce.com)
9
 * @author    Tomasz Kur <[email protected]>
10
 * @author    Mariusz Krzaczkowski <[email protected]>
11
 * @author    Radosław Skrzypczak <[email protected]>
12
 */
13
14
namespace App\Controller;
15
16
/**
17
 * Controller class for views.
18
 */
19
abstract class View extends Base
0 ignored issues
show
Coding Style introduced by
View does not seem to conform to the naming convention (^Abstract|Factory$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
20
{
21
	/** @var \App\Viewer Viewer object. */
22
	protected $viewer;
23
24
	/** {@inheritdoc} */
25
	public function __construct(\App\Request $request)
26
	{
27
		parent::__construct($request);
28
		$this->loadJsConfig($request);
29
		$this->viewer = new \App\Viewer();
30
		$this->viewer->assign('MODULE_NAME', $this->getModuleNameFromRequest($this->request));
0 ignored issues
show
Unused Code introduced by
The call to View::getModuleNameFromRequest() has too many arguments starting with $this->request.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
31
		$this->viewer->assign('VIEW', $this->request->getByType('view', \App\Purifier::ALNUM));
32
		$this->viewer->assign('NONCE', \App\Session::get('CSP_TOKEN'));
33
		$this->viewer->assign('LANGUAGE', \App\Language::getLanguage());
34
		$this->viewer->assign('LANG', \App\Language::getShortLanguageName());
35
		$this->viewer->assign('USER', \App\User::getUser());
36
		$this->viewer->assign('ACTION_NAME', $this->request->getAction());
37
	}
38
39
	/**
40
	 * Check permission.
41
	 *
42
	 * @throws \App\Exceptions\NoPermitted
43
	 *
44
	 * @return void
45
	 */
46
	public function checkPermission(): void
47
	{
48
		$this->getModuleNameFromRequest($this->request);
0 ignored issues
show
Unused Code introduced by
The call to View::getModuleNameFromRequest() has too many arguments starting with $this->request.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
49
		if (!\App\User::getUser()->isPermitted($this->moduleName)) {
50
			throw new \App\Exceptions\AppException('ERR_MODULE_PERMISSION_DENIED');
51
		}
52
	}
53
54
	/** {@inheritdoc} */
55
	public function preProcess($display = true): void
56
	{
57
		if ($this->loginRequired()) {
58
			$this->viewer->assign('MENU', \YF\Modules\Base\Model\Menu::getInstance($this->viewer->getTemplateVars('MODULE_NAME'))->getMenu());
59
		}
60
		$this->viewer->assign('PAGE_TITLE', (\Conf\Config::$siteName ?: \App\Language::translate('LBL_CUSTOMER_PORTAL')) . ' ' . $this->getPageTitle());
61
		$this->viewer->assign('CSS_FILE', $this->getHeaderCss());
62
		$this->viewer->assign('USER_QUICK_MENU', $this->getUserQuickMenuLinks());
63
		if ($display) {
64
			$this->preProcessDisplay();
65
		}
66
	}
67
68
	/**
69
	 * Get page title.
70
	 *
71
	 * @return string
72
	 */
73
	public function getPageTitle(): string
74
	{
75
		$title = \App\Language::translateModule($this->moduleName);
76
		$pageTitle = $this->getBreadcrumbTitle();
77
		if (isset($this->pageTitle)) {
78
			$pageTitle = \App\Language::translate($this->pageTitle);
0 ignored issues
show
Bug introduced by
The property pageTitle does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
79
		}
80
		if ($pageTitle) {
81
			$title .= ' - ' . $pageTitle;
82
		}
83
		return $title;
84
	}
85
86
	/**
87
	 * Get breadcrumb title.
88
	 *
89
	 * @return string
90
	 */
91
	public function getBreadcrumbTitle(): string
92
	{
93
		if (!empty($this->pageTitle)) {
94
			return $this->pageTitle;
95
		}
96
		return '';
97
	}
98
99
	/**
100
	 * Convert scripts path.
101
	 *
102
	 * @param array  $files
103
	 * @param string $fileExtension
104
	 *
105
	 * @return array
106
	 */
107
	public function convertScripts(array $files, string $fileExtension): array
108
	{
109
		$scriptsInstances = [];
110
		foreach ($files as $file) {
111
			[$fileName, $isOptional] = array_pad($file, 2, false);
0 ignored issues
show
Bug introduced by
The variable $fileName does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $isOptional does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
112
			$path = ROOT_DIRECTORY . "/public_html/$fileName";
113
			$script = new \App\Script();
114
			$script->set('type', $fileExtension);
115
			$minFilePath = str_replace('.' . $fileExtension, '.min.' . $fileExtension, $fileName);
116
			if (\App\Config::$minScripts && file_exists(ROOT_DIRECTORY . "/public_html/$minFilePath")) {
117
				$scriptsInstances[] = $script->set('src', PUBLIC_DIRECTORY . $minFilePath . self::getTime($path));
118
			} elseif (file_exists($path)) {
119
				$scriptsInstances[] = $script->set('src', PUBLIC_DIRECTORY . $fileName . self::getTime($path));
120
			} elseif (!$isOptional) {
121
				\App\Log::warning('File not found: ' . $path);
122
			}
123
		}
124
		return $scriptsInstances;
125
	}
126
127
	/**
128
	 * Gets file modification time.
129
	 *
130
	 * @param string $path
131
	 *
132
	 * @return string
133
	 */
134
	public static function getTime(string $path): string
135
	{
136
		$url = '';
137
		if ($fs = filemtime($path)) {
138
			$url = '?s=' . $fs;
139
		}
140
		return $url;
141
	}
142
143
	/**
144
	 * Retrieves css styles that need to loaded in the page.
145
	 *
146
	 * @return \App\Script[]
147
	 */
148
	public function getHeaderCss(): array
149
	{
150
		return $this->convertScripts([
151
			['libraries/@fortawesome/fontawesome-free/css/all.css'],
152
			['libraries/@mdi/font/css/materialdesignicons.css'],
153
			['libraries/bootstrap/dist/css/bootstrap.css'],
154
			['libraries/chosen-js/chosen.css'],
155
			['libraries/bootstrap-chosen/bootstrap-chosen.css'],
156
			['libraries/jQuery-Validation-Engine/css/validationEngine.jquery.css'],
157
			['libraries/bootstrap-tabdrop/css/tabdrop.css'],
158
			['libraries/select2/dist/css/select2.css'],
159
			['libraries/select2-theme-bootstrap4/dist/select2-bootstrap.css'],
160
			['libraries/datatables.net-bs4/css/dataTables.bootstrap4.css'],
161
			['libraries/datatables.net-responsive-bs4/css/responsive.bootstrap4.css'],
162
			['libraries/bootstrap-datepicker/dist/css/bootstrap-datepicker3.css'],
163
			['libraries/bootstrap-daterangepicker/daterangepicker.css'],
164
			['libraries/clockpicker/dist/bootstrap4-clockpicker.css'],
165
			['libraries/jstree-bootstrap-theme/dist/themes/proton/style.css'],
166
			['libraries/jstree/dist/themes/default/style.css'],
167
			['libraries/@pnotify/core/dist/PNotify.css'],
168
			['libraries/@pnotify/confirm/dist/PNotifyConfirm.css'],
169
			['libraries/@pnotify/bootstrap4/dist/PNotifyBootstrap4.css'],
170
			['libraries/@pnotify/mobile/dist/PNotifyMobile.css'],
171
			['libraries/@pnotify/desktop/dist/PNotifyDesktop.css'],
172
			['layouts/resources/icons/additionalIcons.css'],
173
			['layouts/resources/icons/yfm.css'],
174
			['layouts/resources/icons/yfi.css'],
175
			['layouts/' . \App\Viewer::getLayoutName() . '/skins/basic/Main.css'],
176
		], 'css');
177
	}
178
179
	/**
180
	 * Pre process display.
181
	 *
182
	 * @return void
183
	 */
184
	protected function preProcessDisplay(): void
185
	{
186
		if (\App\Session::has('systemError')) {
187
			$this->viewer->assign('ERRORS', \App\Session::get('systemError'));
188
			\App\Session::unset('systemError');
189
		}
190
		$this->viewer->view($this->preProcessTplName(), $this->moduleName);
191
	}
192
193
	/**
194
	 * Get preprocess tpl name.
195
	 *
196
	 * @return string
197
	 */
198
	protected function preProcessTplName(): string
199
	{
200
		return 'Header.tpl';
201
	}
202
203
	/**
204
	 * Get process tpl name.
205
	 *
206
	 * @return string
207
	 */
208
	protected function processTplName(): string
209
	{
210
		return $this->request->getAction() . '/Index.tpl';
211
	}
212
213
	/** {@inheritdoc}  */
214
	protected function postProcessTplName(): string
215
	{
216
		return 'Footer.tpl';
217
	}
218
219
	/** {@inheritdoc} */
220
	public function postProcess(): void
221
	{
222
		if (null === $this->viewer->getTemplateVars('SHOW_FOOTER_BAR')) {
223
			$this->viewer->assign('SHOW_FOOTER_BAR', true);
224
		}
225
		$this->viewer->assign('JS_FILE', $this->getFooterScripts());
226
		if (\App\Config::$debugApi && \App\Session::has('debugApi') && \App\Session::get('debugApi')) {
227
			$this->viewer->assign('DEBUG_API', \App\Session::get('debugApi'));
228
			$this->viewer->view('DebugApi.tpl', $this->moduleName);
229
			\App\Session::set('debugApi', false);
230
		}
231
		$this->viewer->view($this->postProcessTplName(), $this->moduleName);
232
	}
233
234
	/**
235
	 * Scripts.
236
	 *
237
	 * @param bool $loadForModule
238
	 *
239
	 * @return \App\Script[]
240
	 */
241
	public function getFooterScripts(bool $loadForModule = true): array
242
	{
243
		$action = $this->request->getAction();
244
		$languageHandlerShortName = \App\Language::getShortLanguageName();
245
		$fileName = ["libraries/jQuery-Validation-Engine/js/languages/jquery.validationEngine-$languageHandlerShortName.js"];
246
		if (!file_exists(PUBLIC_DIRECTORY . $fileName[0])) {
247
			$fileName = ['libraries/jQuery-Validation-Engine/js/languages/jquery.validationEngine-en.js'];
248
		}
249
		$files = [
250
			['libraries/jquery/dist/jquery.js'],
251
			['libraries/jquery.class.js/jquery.class.js'],
252
			['libraries/block-ui/jquery.blockUI.js'],
253
			['libraries/@pnotify/core/dist/PNotify.js'],
254
			['libraries/@pnotify/mobile/dist/PNotifyMobile.js'],
255
			['libraries/@pnotify/desktop/dist/PNotifyDesktop.js'],
256
			['libraries/@pnotify/confirm/dist/PNotifyConfirm.js'],
257
			['libraries/@pnotify/bootstrap4/dist/PNotifyBootstrap4.js'],
258
			['libraries/@pnotify/font-awesome5/dist/PNotifyFontAwesome5.js'],
259
			['libraries/popper.js/dist/umd/popper.js'],
260
			['vendor/ckeditor/ckeditor/ckeditor.js'],
261
			['vendor/ckeditor/ckeditor/adapters/jquery.js'],
262
			['libraries/bootstrap/dist/js/bootstrap.js'],
263
			['libraries/bootstrap-tabdrop/js/bootstrap-tabdrop.js'],
264
			['libraries/bootstrap-datepicker/dist/js/bootstrap-datepicker.js'],
265
			['libraries/bootstrap-daterangepicker/daterangepicker.js'],
266
			['libraries/bootbox/dist/bootbox.min.js'],
267
			['libraries/chosen-js/chosen.jquery.js'],
268
			['libraries/select2/dist/js/select2.full.js'],
269
			['libraries/moment/min/moment.min.js'],
270
			['libraries/inputmask/dist/jquery.inputmask.js'],
271
			['libraries/datatables.net/js/jquery.dataTables.js'],
272
			['libraries/datatables.net-bs4/js/dataTables.bootstrap4.js'],
273
			['libraries/datatables.net-responsive/js/dataTables.responsive.js'],
274
			['libraries/datatables.net-responsive-bs4/js/responsive.bootstrap4.js'],
275
			['libraries/jQuery-Validation-Engine/js/jquery.validationEngine.js'],
276
			$fileName,
277
			['libraries/jstree/dist/jstree.js'],
278
			['libraries/clockpicker/dist/bootstrap4-clockpicker.js'],
279
			['layouts/resources/validator/BaseValidator.js'],
280
			['layouts/resources/validator/FieldValidator.js'],
281
			['layouts/resources/helper.js'],
282
			['layouts/resources/Field.js'],
283
			['layouts/resources/Connector.js'],
284
			['layouts/resources/app.js'],
285
			['layouts/resources/Fields.js'],
286
			['layouts/resources/ProgressIndicator.js'],
287
			['layouts/' . \App\Viewer::getLayoutName() . '/modules/Base/resources/Header.js'],
288
			['layouts/' . \App\Viewer::getLayoutName() . "/modules/Base/resources/{$action}.js"],
289
		];
290
		if ($loadForModule) {
291
			$moduleName = $this->getModuleNameFromRequest();
292
			$files[] = ['layouts/' . \App\Viewer::getLayoutName() . "/modules/{$moduleName}/resources/{$action}.js", true];
293
		}
294
		return $this->convertScripts($files, 'js');
295
	}
296
297
	/** {@inheritdoc} */
298
	public function validateRequest()
299
	{
300
		$this->request->validateReadAccess();
301
	}
302
303
	/** {@inheritdoc} */
304
	public function postProcessAjax()
305
	{
306
	}
307
308
	/** {@inheritdoc} */
309
	public function preProcessAjax()
310
	{
311
	}
312
313
	/**
314
	 * Get module name from request.
315
	 *
316
	 * @return string
317
	 */
318
	protected function getModuleNameFromRequest(): string
319
	{
320
		if (empty($this->moduleName)) {
321
			$this->moduleName = $this->request->getModule();
322
		}
323
		return $this->moduleName;
324
	}
325
326
	/**
327
	 * Load js config.
328
	 *
329
	 * @param \App\Request $request
330
	 */
331
	public function loadJsConfig(\App\Request $request): void
332
	{
333
		$jsEnv = [
334
			'siteUrl' => \App\Utils::getPublicUrl('', true),
335
			'langPrefix' => \App\Language::getLanguage(),
336
			'langKey' => \App\Language::getShortLanguageName(),
337
			'parentModule' => $request->getByType('parent', 2),
338
		];
339
		foreach ($jsEnv as $key => $value) {
340
			\App\Config::setJsEnv($key, $value);
341
		}
342
	}
343
344
	/**
345
	 * Get the list of user quick menu links.
346
	 *
347
	 * @return array
348
	 */
349
	protected function getUserQuickMenuLinks(): array
350
	{
351
		$user = \App\User::getUser();
352
		$links = [
353
			[
354
				'label' => 'LBL_CHANGE_PASSWORD',
355
				'moduleName' => 'Users',
356
				'data' => ['url' => 'index.php?module=Users&view=PasswordChangeModal'],
357
				'icon' => 'yfi yfi-change-passowrd',
358
				'class' => 'text-decoration-none u-fs-sm text-secondary js-show-modal d-block',
359
				'btnClass' => ' ',
360
				'href' => '#',
361
				'showLabel' => true,
362
			],
363
			[
364
				'label' => 'BTN_YOUR_ACCOUNT_ACCESS_HISTORY',
365
				'moduleName' => 'Users',
366
				'data' => ['url' => 'index.php?module=Users&view=AccessActivityHistoryModal'],
367
				'icon' => 'yfi yfi-login-history',
368
				'class' => 'text-decoration-none u-fs-sm text-secondary js-show-modal d-block',
369
				'btnClass' => ' ',
370
				'href' => '#',
371
				'showLabel' => true,
372
			],
373
		];
374
		if ('PLL_PASSWORD_2FA' === $user->get('login_method') && !$user->isEmpty('authy_methods')) {
375
			$links[] = [
376
				'label' => 'BTN_2FA_TOTP_QR_CODE',
377
				'moduleName' => 'Users',
378
				'data' => ['url' => 'index.php?module=Users&view=TwoFactorAuthenticationModal'],
379
				'icon' => 'fas fa-key',
380
				'class' => 'text-decoration-none u-fs-sm text-secondary js-show-modal d-block',
381
				'btnClass' => ' ',
382
				'href' => '#',
383
				'showLabel' => true,
384
			];
385
		}
386
		return $links;
387
	}
388
}
389