Test Failed
Push — master ( 9287ab...2f3843 )
by Georgi
03:56
created

UI::jsRedirectHomepage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 1
dl 0
loc 15
rs 9.9666
c 0
b 0
f 0
1
<?php 
2
3
namespace Epesi\Core;
4
5
use atk4\ui\jsExpression;
6
use Epesi\Core\System\Modules\Concerns\HasLinks;
7
use Epesi\Core\System\SystemCore;
8
use Epesi\Core\System\Modules\ModuleManager;
9
use Illuminate\Session\TokenMismatchException;
10
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
11
12
class UI extends \atk4\ui\App
13
{
14
	use HasLinks;
15
	
16
	public $version = '2.0.0-alpha1';
17
	
18
	public $cdn = [
19
			'semantic-ui'      => 'https://cdn.jsdelivr.net/npm/[email protected]/dist',
20
	];
21
	
22
	public $always_run = false;
23
	
24
	protected $url_building_ext = '';
25
	
26
	public function __construct($defaults = [])
27
	{
28
		parent::__construct([
29
				'title' => config('epesi.app.title', 'EPESI'),
30
		        'cdn' => array_merge($this->cdn, (array) config('epesi.app.cdn')),
31
				//TODO: set the skin from admin / user selection
32
		        'skin' => config('epesi.app.skin', $this->skin),
33
		        'template_dir' => array_merge(ModuleManager::collect('templates', $this->skin), (array) $this->template_dir)
34
		]);
35
	}
36
	
37
	final public static function module()
38
	{
39
		return SystemCore::class;
40
	}
41
	
42
	public function response()
43
	{
44
		return response($this->render());
45
	}
46
	
47
// 	public function getViewJS($actions)
48
// 	{
49
// 		$ready = new jsFunction($actions);
50
		
51
// 		return "<script page-pjax>\n".
52
// 				(new jQuery($ready))->jsRender().
53
// 				'</script>';
54
// 	}
55
	
56
	public function render()
57
	{	
58
		$this->module()::requireCSS('epesi.css');
59
		
60
		$this->addCsrfToken();
61
		
62
		$this->addFavIcon();
63
		
64
// 		$this->enablePjax();
65
		
66
		ob_start();
67
		
68
		$this->run();
69
		
70
		return ob_get_clean();
71
	}
72
	
73
	public function renderException($exception)
74
	{
75
	    ob_start();
76
	    if ($exception instanceof TokenMismatchException) {
77
	        $this->jsRedirectHomepage(__('Session expired! Redirecting to your home page ...'));
78
	    }
79
	    elseif ($exception instanceof NotFoundHttpException) {
80
	        $this->jsRedirectHomepage(__('Requested page not found! Redirecting to your home page ...'));
81
	    }	    
82
	    else {
83
	        $this->caughtException($exception);
84
	    }
85
	    
86
	    return ob_get_clean();
87
	}
88
	
89
	public function jsRedirectHomepage($message)
90
	{
91
	    $homepageUrl = url(\Epesi\Core\HomePage\Database\Models\HomePage::pathOfUser());
0 ignored issues
show
Bug introduced by
The type Epesi\Core\HomePage\Database\Models\HomePage was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
92
	    
93
	    $redirectJs = $this->jsRedirectConfirm($homepageUrl, $message)->jsRender();
94
	    
95
	    if ($this->isJsonRequest()) {
96
	        $this->outputResponseJSON([
97
	                'success'   => true,
98
	                'message'   => $message,
99
	                'atkjs'   => $redirectJs
100
	        ]);
101
	    }
102
	    else {
103
	        $this->outputResponseHTML('<script>' . $redirectJs . '</script>');
104
	    }
105
	}
106
	
107
	public function jsRedirectConfirm($page, $message)
108
	{
109
	    $redirectJs = $this->jsRedirect($page)->jsRender();
110
	    
111
	    return new jsExpression("if (confirm([])) { $redirectJs }", [$message]);
112
	}
113
	
114
	/**
115
	 * Initialize JS and CSS includes.
116
	 */
117
	public function initIncludes()
118
	{
119
// 		$this->requireJS(asset('js/app.js'));
120
// 		$this->requireCSS(asset('css/app.css'));
121
				
122
		//TODO: include below in app.js and app.css
123
		
124
		$localJs = url('storage/system/js');
125
		$localCss = url('storage/system/css');
126
		
127
		// jQuery
128
		$urlJs = $this->cdn['jquery']?? $localJs;
129
		$this->requireJS($urlJs.'/jquery.min.js');
130
		
131
		// Semantic UI
132
		$urlJs = $this->cdn['semantic-ui']?? $localJs;
133
		$urlCss = $this->cdn['semantic-ui']?? $localCss;
134
		$this->requireJS($urlJs.'/semantic.min.js');
135
		$this->requireCSS($urlCss.'/semantic.min.css');
136
		
137
		// Serialize Object
138
		$urlJs = $this->cdn['serialize-object']?? $localJs;
139
		$this->requireJS($urlJs.'/jquery.serialize-object.min.js');
140
		
141
		// Agile UI
142
		$urlJs = $this->cdn['atk']?? $localJs;
143
		$urlCss = $this->cdn['atk']?? $localCss;
144
		$this->requireJS($urlJs.'/atkjs-ui.min.js');
145
		$this->requireCSS($urlCss.'/agileui.css');
146
		
147
		// Draggable
148
		$urlJs = $this->cdn['draggable']?? $localJs;
149
		$this->requireJS($urlJs.'/draggable.bundle.js');
150
		
151
		// jQuery niceScroll	
152
		$urlJs = $this->cdn['jquery-nicescroll']?? $localJs;
153
		$this->requireJS($urlJs.'/jquery.nicescroll.js');
154
		
155
		// clipboard.js
156
		$urlJs = $this->cdn['clipboardjs']?? $localJs;
157
		$this->requireJS($urlJs.'/clipboard.js');
158
	}
159
	
160
	public function addCsrfToken()
161
	{
162
		$this->html->template->appendHTML('meta', $this->getTag('meta', ['name' => 'csrf-token', 'content' => csrf_token()]));
0 ignored issues
show
Bug introduced by
array('name' => 'csrf-to...ntent' => csrf_token()) of type array<string,string> is incompatible with the type string expected by parameter $attr of atk4\ui\App::getTag(). ( Ignorable by Annotation )

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

162
		$this->html->template->appendHTML('meta', $this->getTag('meta', /** @scrutinizer ignore-type */ ['name' => 'csrf-token', 'content' => csrf_token()]));
Loading history...
163
164
		$this->addJS('$.ajaxSetup({
165
			headers: {
166
				\'X-CSRF-TOKEN\': $(\'meta[name="csrf-token"]\').attr(\'content\')
167
			}
168
		})');
169
	}
170
	
171
	public function addFavIcon()
172
	{
173
		$this->html->template->appendHTML('HEAD', $this->getTag('link', ['rel' => 'shortcut icon', 'href' => config('epesi.app.favicon', url('favicon.png'))]));
0 ignored issues
show
Bug introduced by
array('rel' => 'shortcut...', url('favicon.png'))) of type array<string,mixed|string> is incompatible with the type string expected by parameter $attr of atk4\ui\App::getTag(). ( Ignorable by Annotation )

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

173
		$this->html->template->appendHTML('HEAD', $this->getTag('link', /** @scrutinizer ignore-type */ ['rel' => 'shortcut icon', 'href' => config('epesi.app.favicon', url('favicon.png'))]));
Loading history...
174
	}
175
	
176
	public function enablePjax()
177
	{
178
		// pjax library
179
// 		$this->requireJS('https://cdn.jsdelivr.net/npm/pjax/pjax.js');
180
		
181
// 		$this->html->template->appendHTML('HEAD', '<script>
182
// 			$(function(){
183
// 				var pjax = new Pjax({
184
// 						"elements": ".pjax", 
185
// 						"selectors": [".atk-layout", "head > script[page-pjax]", "head > title"]
186
// 				});
187
// 			});
188
			
189
// 		</script>');
190
		
191
		// pjax-api library
192
		$this->requireJS('https://cdn.jsdelivr.net/npm/pjax-api@latest');
193
194
		$this->html->template->appendHTML('HEAD', '<script>
195
196
			$(function(){		
197
				const { Pjax } = require("pjax-api");		
198
				new Pjax({
199
						"links": ".pjax", 
200
						"areas": [".atk-layout", "head > script[page-pjax]", "head > title"]
201
				});
202
			});
203
			
204
		</script>');
205
206
		// common
207
		$this->addJs('$(".pjax").click(function(e) {
208
				window.onbeforeunload(e);
209
				
210
				if (e.returnValue == "unsaved" && ! confirm("Unsaved data. Continue?")) {
211
 					e.stopImmediatePropagation();
212
					window.stop();
213
 				}
214
		});');		
215
	}
216
	
217
	public function addJs($js, $args = [])
218
	{
219
		$this->html->js(true, new jsExpression($js, $args));
220
	}
221
222
	/**
223
	 * Override default method to make sure js script is included only once
224
	 * 
225
	 * {@inheritDoc}
226
	 * @see \atk4\ui\App::requireJS()
227
	 */
228
	public function requireJS($url, $isAsync = false, $isDefer = false)
229
	{
230
		static $cache;
231
		
232
		$key = md5(serialize(func_get_args()));
233
		
234
		if (! isset($cache[$key])) {
235
			$cache[$key] = true;
236
			
237
			parent::requireJS($url, $isAsync, $isDefer);
238
		}
239
				
240
		return $this;
241
	}
242
		
243
	/**
244
	 * Set the breadcrumb location
245
	 * 
246
	 * @param array|string $location
247
	 * @return null
248
	 */
249
	public function setLocation($location)
250
	{
251
		return $this->layout->setLocation($location);
0 ignored issues
show
Bug introduced by
The method setLocation() does not exist on atk4\ui\Layout\Generic. ( Ignorable by Annotation )

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

251
		return $this->layout->/** @scrutinizer ignore-call */ setLocation($location);

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...
252
	}
253
	
254
	public function packageInfo()
255
	{
256
		$content = file_get_contents(__DIR__ . '/../composer.json');
257
		
258
		return json_decode($content, true);
259
	}
260
}