Completed
Push — master ( 55f351...d9189f )
by Jean-Christophe
03:28
created

JqueryAjaxTrait::_getOnAjaxDone()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 16
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 13
nc 7
nop 4
1
<?php
2
3
namespace Ajax\common\traits;
4
5
use Ajax\service\JString;
6
use Ajax\service\Javascript;
7
use Ajax\service\AjaxTransition;
8
9
10
/**
11
 * @author jc
12
 * @property array $jquery_code_for_compile
13
 * @property Ajax\JsUtils $jsUtils
14
 * @property array $params
15
 */
16
trait JqueryAjaxTrait {
17
	protected $ajaxTransition;
18
	protected $ajaxLoader='<span></span><span></span><span></span><span></span><span></span>';
19
20
	abstract public function _add_event($element, $js, $event, $preventDefault=false, $stopPropagation=false,$immediatly=true);
21
	protected function addLoading(&$retour, $responseElement) {
22
		$loading_notifier='<div class="ajax-loader">';
23
		if ($this->ajaxLoader=='') {
24
			$loading_notifier.="Loading...";
25
		} else {
26
			$loading_notifier.=$this->ajaxLoader;
27
		}
28
		$loading_notifier.='</div>';
29
		$retour.="$({$responseElement}).empty();\n";
30
		$retour.="\t\t$({$responseElement}).prepend('{$loading_notifier}');\n";
31
	}
32
33
	public function _get($url, $params="{}", $responseElement="", $jsCallback=NULL, $attr="id", $hasLoader=true,$jqueryDone="html",$ajaxTransition=null,$immediatly=false) {
34
		return $this->_ajax("get", $url,$params,$responseElement,$jsCallback,$attr,$hasLoader,$jqueryDone,$ajaxTransition,$immediatly);
35
	}
36
	public function _post($url, $params="{}", $responseElement="", $jsCallback=NULL, $attr="id", $hasLoader=true,$jqueryDone="html",$ajaxTransition=null,$immediatly=false) {
37
		return $this->_ajax("post", $url,$params,$responseElement,$jsCallback,$attr,$hasLoader,$jqueryDone,$ajaxTransition,$immediatly);
38
	}
39
40
	protected function _ajax($method,$url, $params="{}", $responseElement="", $jsCallback=NULL, $attr="id", $hasLoader=true,$jqueryDone="html",$ajaxTransition=null,$immediatly=false) {
41
		if(JString::isNull($params)){$params="{}";}
42
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
43
		$retour=$this->_getAjaxUrl($url, $attr);
44
		$responseElement=$this->_getResponseElement($responseElement);
45
		$retour.="var self=this;\n";
46
		if($hasLoader===true){
47
			$this->addLoading($retour, $responseElement);
48
		}
49
		$retour.="$.".$method."(url,".$params.").done(function( data ) {\n";
50
		$retour.=$this->_getOnAjaxDone($responseElement, $jqueryDone,$ajaxTransition,$jsCallback)."});\n";
51
		if ($immediatly)
52
			$this->jquery_code_for_compile[]=$retour;
53
			return $retour;
54
	}
55
56
	protected function setAjaxDataCall($params){
57
		$result=null;
58
		if(!\is_callable($params) && \method_exists("Ajax\service\AjaxTransition",$params)){
59
			$result=function ($responseElement,$jqueryDone="html") use($params){
60
				return AjaxTransition::{$params}($responseElement,$jqueryDone);
61
			};
62
		}
63
		return $result;
64
	}
65
66
	protected function _getAjaxUrl($url,$attr){
67
		$url=$this->_correctAjaxUrl($url);
68
		$retour="url='".$url."';";
69
		$slash="/";
70
		if(JString::endswith($url, "/")===true)
71
			$slash="";
72
		if(JString::isNotNull($attr)){
73
			if ($attr==="value")
74
				$retour.="url=url+'".$slash."'+$(this).val();\n";
75
			elseif ($attr==="html")
76
			$retour.="url=url+'".$slash."'+$(this).html();\n";
77
			elseif($attr!=null && $attr!=="")
78
					$retour.="url=url+'".$slash."'+($(this).attr('".$attr."')||'');\n";
79
		}
80
		return $retour;
81
	}
82
83
	protected function _getOnAjaxDone($responseElement,$jqueryDone,$ajaxTransition,$jsCallback){
84
		$retour="";$call=null;
85
		if ($responseElement!=="") {
86
			if(isset($ajaxTransition)){
87
				$call=$this->setAjaxDataCall($ajaxTransition);
88
			}elseif(isset($this->ajaxTransition)){
89
				$call=$this->ajaxTransition;
90
			}
91
			if(\is_callable($call))
92
				$retour="\t".$call($responseElement,$jqueryDone).";\n";
93
			else
94
				$retour="\t$({$responseElement}).{$jqueryDone}( data );\n";
95
		}
96
		$retour.="\t".$jsCallback."\n";
97
		return $retour;
98
	}
99
100
	protected function _getResponseElement($responseElement){
101
		if ($responseElement!=="") {
102
			$responseElement=Javascript::prep_value($responseElement);
103
		}
104
		return $responseElement;
105
	}
106
107
	protected function _correctAjaxUrl($url) {
108
		if ($url!=="/" && JString::endsWith($url, "/")===true)
109
			$url=substr($url, 0, strlen($url)-1);
110
		if (strncmp($url, 'http://', 7)!=0&&strncmp($url, 'https://', 8)!=0) {
111
			$url=$this->jsUtils->getUrl($url);
112
		}
113
		return $url;
114
	}
115
116
	/**
117
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name
118
	 * @param string $url the request address
119
	 * @param string $params Paramètres passés au format JSON
120
	 * @param string $method Method use
121
	 * @param string $jsCallback javascript code to execute after the request
122
	 * @param boolean $immediatly
123
	 */
124
	public function _json($url, $method="get", $params="{}", $jsCallback=NULL, $attr="id", $context="document",$immediatly=false) {
125
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
126
		$retour=$this->_getAjaxUrl($url, $attr);
127
		$retour.="$.{$method}(url,".$params.").done(function( data ) {\n";
128
		$retour.="\tdata=$.parseJSON(data);for(var key in data){"
129
				."if($('#'+key,".$context.").length){ if($('#'+key,".$context.").is('[value]')) { $('#'+key,".$context.").val(data[key]);} else { $('#'+key,".$context.").html(data[key]); }}};\n";
130
				$retour.="\t".$jsCallback."\n".
131
						"\t$(document).trigger('jsonReady',[data]);\n".
132
						"});\n";
133
				if ($immediatly)
134
					$this->jquery_code_for_compile[]=$retour;
135
					return $retour;
136
	}
137
138
	/**
139
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element
140
	 * @param string $element
141
	 * @param string $event
142
	 * @param string $url the request address
143
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","immediatly"=>true)
144
	 */
145 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...
146
		$preventDefault=true;
147
		$stopPropagation=true;
148
		$jsCallback=null;
149
		$attr="id";
150
		$method="get";
151
		$context="document";
152
		$params="{}";
153
		$immediatly=true;
154
		extract($parameters);
155
		return $this->_add_event($element, $this->_json($url,$method, $params,$jsCallback, $attr,$context), $event, $preventDefault, $stopPropagation,$immediatly);
156
	}
157
158
	/**
159
	 * Makes an ajax request and receives a JSON array data types by copying and assigning them to the DOM elements with the same name
160
	 * @param string $url the request address
161
	 * @param string $params Paramètres passés au format JSON
162
	 * @param string $method Method use
163
	 * @param string $jsCallback javascript code to execute after the request
164
	 * @param string $context jquery DOM element, array container.
165
	 * @param boolean $immediatly
166
	 */
167
	public function _jsonArray($maskSelector, $url, $method="get", $params="{}", $jsCallback=NULL, $attr="id", $context=null,$immediatly=false) {
168
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
169
		$retour=$this->_getAjaxUrl($url, $attr);
170
		if($context===null){
171
			$appendTo="\t\tnewElm.appendTo($('".$maskSelector."').parent());\n";
172
			$newElm = "$('#'+newId)";
173
		}else{
174
			$appendTo="\t\tnewElm.appendTo(".$context.");\n";
175
			$newElm = $context.".find('#'+newId)";
176
		}
177
		$retour.="var self = $(this);\n$.{$method}(url,".$params.").done(function( data ) {\n";
178
		$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";
179
		$retour.= $appendTo;
180
		$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";
181
		$retour.="\t$(document).trigger('jsonReady',[data]);\n";
182
		$retour.="\t".$jsCallback."\n"."});\n";
183
		if ($immediatly)
184
			$this->jquery_code_for_compile[]=$retour;
185
			return $retour;
186
	}
187
	/**
188
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element
189
	 * @param string $element
190
	 * @param string $event
191
	 * @param string $url the request address
192
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get", "context"=>null)
193
	 */
194 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...
195
		$preventDefault=true;
196
		$stopPropagation=true;
197
		$jsCallback=null;
198
		$attr="id";
199
		$method="get";
200
		$context = null;
201
		$params="{}";
202
		$immediatly=true;
203
		extract($parameters);
204
		return $this->_add_event($element, $this->_jsonArray($maskSelector,$url,$method, $params,$jsCallback, $attr, $context), $event, $preventDefault, $stopPropagation,$immediatly);
205
	}
206
207
	public function _postForm($url, $form, $responseElement, $validation=false, $jsCallback=NULL, $attr="id", $hasLoader=true,$jqueryDone="html",$ajaxTransition=null,$immediatly=false) {
208
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
209
		$retour=$this->_getAjaxUrl($url, $attr);
210
		$retour.="\nvar params=$('#".$form."').serialize();\n";
211
		$responseElement=$this->_getResponseElement($responseElement);
212
		$retour.="var self=this;\n";
213
		if($hasLoader===true){
214
			$this->addLoading($retour, $responseElement);
215
		}
216
		$retour.="$.post(url,params).done(function( data ) {\n";
217
		$retour.=$this->_getOnAjaxDone($responseElement, $jqueryDone,$ajaxTransition,$jsCallback)."});\n";
218
219
		if ($validation) {
220
			$retour="$('#".$form."').validate({submitHandler: function(form) {
221
			".$retour."
222
			}});\n";
223
			$retour.="$('#".$form."').submit();\n";
224
		}
225
		if ($immediatly)
226
			$this->jquery_code_for_compile[]=$retour;
227
			return $retour;
228
	}
229
230
	/**
231
	 * Effectue un get vers $url sur l'évènement $event de $element en passant les paramètres $params
232
	 * puis affiche le résultat dans $responseElement
233
	 * @param string $element
234
	 * @param string $event
235
	 * @param string $url
236
	 * @param string $params queryString parameters (JSON format). default : {}
237
	 * @param string $responseElement
238
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxTransition"=>null,"jqueryDone"=>"html")
239
	 */
240 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...
241
		$preventDefault=true;
242
		$stopPropagation=true;
243
		$jsCallback=null;
244
		$attr="id";
245
		$hasLoader=true;
246
		$immediatly=true;
247
		$jqueryDone="html";
248
		$ajaxTransition=null;
249
		extract($parameters);
250
		return $this->_add_event($element, $this->_get($url, $params, $responseElement, $jsCallback, $attr,$hasLoader,$jqueryDone,$ajaxTransition), $event, $preventDefault, $stopPropagation,$immediatly);
251
	}
252
253
	/**
254
	 * Effectue un post vers $url sur l'évènement $event de $element en passant les paramètres $params
255
	 * puis affiche le résultat dans $responseElement
256
	 * @param string $element
257
	 * @param string $event
258
	 * @param string $url
259
	 * @param string $params queryString parameters (JSON format). default : {}
260
	 * @param string $responseElement
261
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxTransition"=>null)
262
	 */
263 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...
264
		$preventDefault=true;
265
		$stopPropagation=true;
266
		$jsCallback=null;
267
		$attr="id";
268
		$hasLoader=true;
269
		$immediatly=true;
270
		$jqueryDone="html";
271
		$ajaxTransition=null;
272
		extract($parameters);
273
		return $this->_add_event($element, $this->_post($url, $params, $responseElement, $jsCallback, $attr,$hasLoader,$jqueryDone,$ajaxTransition), $event, $preventDefault, $stopPropagation,$immediatly);
274
	}
275
276
	/**
277
	 * Effectue un post vers $url sur l'évènement $event de $element en passant les paramètres du formulaire $form
278
	 * puis affiche le résultat dans $responseElement
279
	 * @param string $element
280
	 * @param string $event
281
	 * @param string $url
282
	 * @param string $form
283
	 * @param string $responseElement
284
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"validation"=>false,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxTransition"=>null,"immediatly"=>true)
285
	 */
286
	public function _postFormOn($event,$element, $url, $form, $responseElement="", $parameters=array()) {
287
		$preventDefault=true;
288
		$stopPropagation=true;
289
		$validation=false;
290
		$jsCallback=null;
291
		$attr="id";
292
		$hasLoader=true;
293
		$immediatly=true;
294
		$jqueryDone="html";
295
		$ajaxTransition=null;
296
		extract($parameters);
297
		return $this->_add_event($element, $this->_postForm($url, $form, $responseElement, $validation, $jsCallback, $attr,$hasLoader,$jqueryDone,$ajaxTransition), $event, $preventDefault, $stopPropagation,$immediatly);
298
	}
299
}