JqueryAjaxTrait   B
last analyzed

Complexity

Total Complexity 41

Size/Duplication

Total Lines 259
Duplicated Lines 21.24 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 41
c 0
b 0
f 0
lcom 1
cbo 1
dl 55
loc 259
rs 8.2769

18 Methods

Rating   Name   Duplication   Size   Complexity  
_prep_value() 0 1 ?
_add_event() 0 1 ?
A addLoading() 0 11 2
A _get() 0 3 1
A _post() 0 3 1
B _ajax() 0 15 5
B _getAjaxUrl() 0 14 6
A _getOnAjaxDone() 0 8 2
A _getResponseElement() 0 6 2
B _correctAjaxUrl() 0 8 5
A _json() 0 13 3
A _jsonOn() 12 12 1
A _jsonArray() 0 20 4
A _jsonArrayOn() 12 12 1
B _postForm() 0 22 5
A _getOn() 10 10 1
A _postOn() 10 10 1
A _postFormOn() 11 11 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like JqueryAjaxTrait 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 JqueryAjaxTrait, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Ajax\common\traits;
4
5
use Ajax\service\JString;
6
use Ajax\service\PhalconUtils;
7
use Symfony\Component\Config\Definition\Exception\Exception;
8
trait JqueryAjaxTrait {
9
10
	protected $ajaxLoader='<span></span><span></span><span></span><span></span><span></span>';
11
12
	public abstract function _prep_value($value);
13
	public abstract function _add_event($element, $js, $event, $preventDefault=false, $stopPropagation=false,$immediatly=true);
14
	protected function addLoading(&$retour, $responseElement) {
15
		$loading_notifier='<div class="ajax-loader">';
16
		if ($this->ajaxLoader=='') {
17
			$loading_notifier.="Loading...";
18
		} else {
19
			$loading_notifier.=$this->ajaxLoader;
20
		}
21
		$loading_notifier.='</div>';
22
		$retour.="$({$responseElement}).empty();\n";
23
		$retour.="\t\t$({$responseElement}).prepend('{$loading_notifier}');\n";
24
	}
25
26
	public function _get($url, $params="{}", $responseElement="", $jsCallback=NULL, $attr="id", $hasLoader=true,$immediatly=false) {
27
		return $this->_ajax("get", $url,$params,$responseElement,$jsCallback,$attr,$hasLoader,$immediatly);
28
	}
29
	public function _post($url, $params="{}", $responseElement="", $jsCallback=NULL, $attr="id", $hasLoader=true,$immediatly=false) {
30
		return $this->_ajax("post", $url,$params,$responseElement,$jsCallback,$attr,$hasLoader,$immediatly);
31
	}
32
33
	protected function _ajax($method,$url, $params="{}", $responseElement="", $jsCallback=NULL, $attr="id", $hasLoader=true,$immediatly=false) {
34
		if(JString::isNull($params)){$params="{}";}
35
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
36
		$retour=$this->_getAjaxUrl($url, $attr);
37
		$responseElement=$this->_getResponseElement($responseElement);
38
		$retour.="var self=this;\n";
39
		if($hasLoader===true){
40
			$this->addLoading($retour, $responseElement);
41
		}
42
		$retour.="$.".$method."(url,".$params.").done(function( data ) {\n";
43
		$retour.=$this->_getOnAjaxDone($responseElement, $jsCallback)."});\n";
44
		if ($immediatly)
45
			$this->jquery_code_for_compile[]=$retour;
0 ignored issues
show
Bug introduced by
The property jquery_code_for_compile 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...
46
			return $retour;
47
	}
48
49
	protected function _getAjaxUrl($url,$attr){
50
		$url=$this->_correctAjaxUrl($url);
51
		$retour="url='".$url."';\n";
52
		$slash="/";
53
		if(JString::endswith($url, "/")===true)
54
			$slash="";
55
		if(JString::isNotNull($attr)){
56
			if ($attr=="value")
57
				$retour.="url=url+'".$slash."'+$(this).val();\n";
58
				else if($attr!=null && $attr!=="")
59
					$retour.="url=url+'".$slash."'+($(this).attr('".$attr."')||'');\n";
60
		}
61
		return $retour;
62
	}
63
64
	protected function _getOnAjaxDone($responseElement,$jsCallback){
65
		$retour="";
66
		if ($responseElement!=="") {
67
			$retour="\t$({$responseElement}).html( data );\n";
68
		}
69
		$retour.="\t".$jsCallback."\n";
70
		return $retour;
71
	}
72
73
	protected function _getResponseElement($responseElement){
74
		if ($responseElement!=="") {
75
			$responseElement=$this->_prep_value($responseElement);
76
		}
77
		return $responseElement;
78
	}
79
80
	protected function _correctAjaxUrl($url) {
81
		if ($url!=="/" && JString::endsWith($url, "/")===true)
82
			$url=substr($url, 0, strlen($url)-1);
83
		if (strncmp($url, 'http://', 7)!=0&&strncmp($url, 'https://', 8)!=0) {
84
			$url=$this->jsUtils->getUrl($url);
0 ignored issues
show
Bug introduced by
The property jsUtils 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...
85
		}
86
		return $url;
87
	}
88
89
	/**
90
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name
91
	 * @param string $url the request address
92
	 * @param string $params Paramètres passés au format JSON
93
	 * @param string $method Method use
94
	 * @param string $jsCallback javascript code to execute after the request
95
	 * @param boolean $immediatly
96
	 */
97
	public function _json($url, $method="get", $params="{}", $jsCallback=NULL, $attr="id", $context="document",$immediatly=false) {
98
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
99
		$retour=$this->_getAjaxUrl($url, $attr);
100
		$retour.="$.{$method}(url,".$params.").done(function( data ) {\n";
101
		$retour.="\tdata=$.parseJSON(data);for(var key in data){"
102
				."if($('#'+key,".$context.").length){ if($('#'+key,".$context.").is('[value]')) { $('#'+key,".$context.").val(data[key]);} else { $('#'+key,".$context.").html(data[key]); }}};\n";
103
				$retour.="\t".$jsCallback."\n".
104
						"\t$(document).trigger('jsonReady',[data]);\n".
105
						"});\n";
106
				if ($immediatly)
107
					$this->jquery_code_for_compile[]=$retour;
108
					return $retour;
109
	}
110
111
	/**
112
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element
113
	 * @param string $element
114
	 * @param string $event
115
	 * @param string $url the request address
116
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","immediatly"=>true)
117
	 */
118 View Code Duplication
	public function _jsonOn($event,$element, $url,$parameters=array()) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
		$preventDefault=true;
120
		$stopPropagation=true;
121
		$jsCallback=null;
122
		$attr="id";
123
		$method="get";
124
		$context="document";
125
		$params="{}";
126
		$immediatly=true;
127
		extract($parameters);
128
		return $this->_add_event($element, $this->_json($url,$method, $params,$jsCallback, $attr,$context), $event, $preventDefault, $stopPropagation,$immediatly);
129
	}
130
131
	/**
132
	 * Makes an ajax request and receives a JSON array data types by copying and assigning them to the DOM elements with the same name
133
	 * @param string $url the request address
134
	 * @param string $params Paramètres passés au format JSON
135
	 * @param string $method Method use
136
	 * @param string $jsCallback javascript code to execute after the request
137
	 * @param string $context jquery DOM element, array container.
138
	 * @param boolean $immediatly
139
	 */
140
	public function _jsonArray($maskSelector, $url, $method="get", $params="{}", $jsCallback=NULL, $attr="id", $context=null,$immediatly=false) {
141
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
142
		$retour=$this->_getAjaxUrl($url, $attr);
143
		if($context===null){
144
			$appendTo="\t\tnewElm.appendTo($('".$maskSelector."').parent());\n";
145
			$newElm = "$('#'+newId)";
146
		}else{
147
			$appendTo="\t\tnewElm.appendTo(".$context.");\n";
148
			$newElm = $context.".find('#'+newId)";
149
		}
150
		$retour.="var self = $(this);\n$.{$method}(url,".$params.").done(function( data ) {\n";
151
		$retour.="\tdata=$.parseJSON(data);$.each(data, function(index, value) {\n"."\tvar created=false;var maskElm=$('".$maskSelector."').first();maskElm.hide();"."\tvar newId=(maskElm.attr('id') || 'mask')+'-'+index;"."\tvar newElm=".$newElm.";\n"."\tif(!newElm.length){\n"."\t\tnewElm=maskElm.clone();newElm.attr('id',newId);\n";
152
		$retour.= $appendTo;
153
		$retour.="\t}\n"."\tfor(var key in value){\n"."\t\t\tvar html = $('<div />').append($(newElm).clone()).html();\n"."\t\t\tif(html.indexOf('[['+key+']]')>-1){\n"."\t\t\t\tcontent=$(html.split('[['+key+']]').join(value[key]));\n"."\t\t\t\t$(newElm).replaceWith(content);newElm=content;\n"."\t\t\t}\n"."\t\tvar sel='[data-id=\"'+key+'\"]';if($(sel,newElm).length){\n"."\t\t\tvar selElm=$(sel,newElm);\n"."\t\t\t if(selElm.is('[value]')) { selElm.attr('value',value[key]);selElm.val(value[key]);} else { selElm.html(value[key]); }\n"."\t\t}\n"."}\n"."\t$(newElm).show(true);"."\n"."\t$(newElm).removeClass('hide');"."});\n";
154
		$retour.="\t$(document).trigger('jsonReady',[data]);\n";
155
		$retour.="\t".$jsCallback."\n"."});\n";
156
		if ($immediatly)
157
			$this->jquery_code_for_compile[]=$retour;
158
			return $retour;
159
	}
160
	/**
161
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element
162
	 * @param string $element
163
	 * @param string $event
164
	 * @param string $url the request address
165
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get", "context"=>null)
166
	 */
167 View Code Duplication
	public function _jsonArrayOn($event,$element, $maskSelector,$url,$parameters=array()) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
168
		$preventDefault=true;
169
		$stopPropagation=true;
170
		$jsCallback=null;
171
		$attr="id";
172
		$method="get";
173
		$context = null;
174
		$params="{}";
175
		$immediatly=true;
176
		extract($parameters);
177
		return $this->_add_event($element, $this->_jsonArray($maskSelector,$url,$method, $params,$jsCallback, $attr, $context), $event, $preventDefault, $stopPropagation,$immediatly);
178
	}
179
180
	public function _postForm($url, $form, $responseElement, $validation=false, $jsCallback=NULL, $attr="id", $hasLoader=true,$immediatly=false) {
181
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
182
		$retour=$this->_getAjaxUrl($url, $attr);
183
		$retour.="\nvar params=$('#".$form."').serialize();\n";
184
		$responseElement=$this->_getResponseElement($responseElement);
185
		$retour.="var self=this;\n";
186
		if($hasLoader===true){
187
			$this->addLoading($retour, $responseElement);
188
		}
189
		$retour.="$.post(url,params).done(function( data ) {\n";
190
		$retour.=$this->_getOnAjaxDone($responseElement, $jsCallback)."});\n";
191
192
		if ($validation) {
193
			$retour="$('#".$form."').validate({submitHandler: function(form) {
194
			".$retour."
195
			}});\n";
196
			$retour.="$('#".$form."').submit();\n";
197
		}
198
		if ($immediatly)
199
			$this->jquery_code_for_compile[]=$retour;
200
			return $retour;
201
	}
202
203
	/**
204
	 * Effectue un get vers $url sur l'évènement $event de $element en passant les paramètres $params
205
	 * puis affiche le résultat dans $responseElement
206
	 * @param string $element
207
	 * @param string $event
208
	 * @param string $url
209
	 * @param string $params queryString parameters (JSON format). default : {}
210
	 * @param string $responseElement
211
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true)
212
	 */
213 View Code Duplication
	public function _getOn($event,$element, $url, $params="{}", $responseElement="", $parameters=array()) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
214
		$preventDefault=true;
215
		$stopPropagation=true;
216
		$jsCallback=null;
217
		$attr="id";
218
		$hasLoader=true;
219
		$immediatly=true;
220
		extract($parameters);
221
		return $this->_add_event($element, $this->_get($url, $params, $responseElement, $jsCallback, $attr,$hasLoader), $event, $preventDefault, $stopPropagation,$immediatly);
222
	}
223
224
	/**
225
	 * Effectue un post vers $url sur l'évènement $event de $element en passant les paramètres $params
226
	 * puis affiche le résultat dans $responseElement
227
	 * @param string $element
228
	 * @param string $event
229
	 * @param string $url
230
	 * @param string $params queryString parameters (JSON format). default : {}
231
	 * @param string $responseElement
232
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true)
233
	 */
234 View Code Duplication
	public function _postOn($event,$element, $url, $params="{}", $responseElement="", $parameters=array()) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
235
		$preventDefault=true;
236
		$stopPropagation=true;
237
		$jsCallback=null;
238
		$attr="id";
239
		$hasLoader=true;
240
		$immediatly=true;
241
		extract($parameters);
242
		return $this->_add_event($element, $this->_post($url, $params, $responseElement, $jsCallback, $attr,$hasLoader), $event, $preventDefault, $stopPropagation,$immediatly);
243
	}
244
245
	/**
246
	 * Effectue un post vers $url sur l'évènement $event de $element en passant les paramètres du formulaire $form
247
	 * puis affiche le résultat dans $responseElement
248
	 * @param string $element
249
	 * @param string $event
250
	 * @param string $url
251
	 * @param string $form
252
	 * @param string $responseElement
253
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"validation"=>false,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"immediatly"=>true)
254
	 */
255 View Code Duplication
	public function _postFormOn($event,$element, $url, $form, $responseElement="", $parameters=array()) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
256
		$preventDefault=true;
257
		$stopPropagation=true;
258
		$validation=false;
259
		$jsCallback=null;
260
		$attr="id";
261
		$hasLoader=true;
262
		$immediatly=true;
263
		extract($parameters);
264
		return $this->_add_event($element, $this->_postForm($url, $form, $responseElement, $validation, $jsCallback, $attr,$hasLoader), $event, $preventDefault, $stopPropagation,$immediatly);
265
	}
266
}