src/Proxy/jQueryServer.js   B
last analyzed

Complexity

Total Complexity 42
Complexity/F 2.33

Size

Lines of Code 185
Function Count 18

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 9
dl 0
loc 185
rs 8.295
c 0
b 0
f 0
wmc 42
mnd 6
bc 32
fnc 18
bpm 1.7777
cpm 2.3333
noi 14

10 Functions

Rating   Name   Duplication   Size   Complexity  
A jQuery.extend.server 0 19 1
B s.array 0 19 5
A s.null 0 3 1
A 0 5 2
C s.object 0 25 7
A s.number 0 3 2
B $.parseJSON 0 9 5
A s.string 0 15 2
A $.toJSON 0 4 3
A s.boolean 0 3 1

How to fix   Complexity   

Complexity

Complex classes like src/Proxy/jQueryServer.js 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.

1
/**
2
 * jQuery Server Plugin
3
 *
4
 * Server-side Ajax requests supporting jQuery manipulations
5
 * before sending content to the browser.
6
 * 
7
 * Example:
8
 * $.server({url: ${URL})
9
 * 	.find('.my-class')
10
 * 	.client(${CALLBACK});
11
 *
12
 * @version 0.5.1
13
 * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
14
 * @link http://code.google.com/p/phpquery/wiki/jQueryServer
15
 * @link http://code.google.com/p/phpquery/
16
 */
17
jQuery.extend({
18
	serverConfig: function() {
19
		if (typeof jQueryServerConfig != 'undefined')
0 ignored issues
show
Bug introduced by
The variable jQueryServerConfig seems to be never declared. If this is a global, consider adding a /** global: jQueryServerConfig */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
20
			return jQueryServerConfig;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
21
		return {};
22
	}(),
23
	server: function(options){
24
		// set default url
25
		if (! jQuery.serverConfig.url)
26
			jQuery.serverConfig.url = jQuery('script[src$=jquery.js]')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
27
				.attr('src').replace(/jquery\.js$/, '')
28
				+'jQueryServer.php';
29
		// this is cache object
30
		var objectCache = {};
31
		// dump all jQuery methods, but only once
32
		// $.each doesn't work ?
33
		for( var i in jQuery.fn) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
34
			// closure to preserve loop iterator in scope
35
			(function(){
36
				var name = i;
0 ignored issues
show
introduced by
The variable i is changed by the for-each loop on line 33. Only the value of the last iteration will be visible in this function if it is called outside of the loop.
Loading history...
37
				// create dummy method
38
				objectCache[name] = function(){
39
					// create method data object
40
					var data = {
41
						method: name,
42
						arguments: []
43
					};
44
					// collect arguments
45
					$.each(arguments, function(k, v){
46
						data.arguments.push(v);
47
					});
48
					// push data into stack
49
					this.stack.push(data);
50
					// preserve chain
51
					return this;
52
				}
53
			})();
54
		}
55
		/**
56
		 * Fetches results from phpQuery.
57
		 * 
58
		 * @param {Function} callback	Optional. Turns on async request.
0 ignored issues
show
Documentation introduced by
The parameter callback does not exist. Did you maybe forget to remove this comment?
Loading history...
59
		 * First parameter for callback is usually an JSON array of mathed elements. Use $(result) to append it to DOM.
60
		 * It can also be a boolean value or string, depending on last method called.
61
		 */
62
		objectCache.client = function(success, error){
63
//			console.log(this.stack.toSource());
64
//			success = success || function(){
65
//				return $result;
66
//			};
67
			$.ajax({
68
				type: 'POST',
69
				data: {data: $.toJSON(this.stack)},
70
				async: false,
71
				// jQuery.server.config ???
72
				url: jQuery.serverConfig.url,
73
//				success: function(response){
74
//					var $result = jQuery();
75
//					$.each(response, function(v) {
76
//						$result.add(v);
77
//					})
78
//					success.call(null, $result);
79
//				},
80
//				success: success,
81
				success: function(response){
82
					if (options['dataType'] == 'json')
83
						response = $.parseJSON(response);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
84
					success(response);
85
				},
86
				error: error
87
			})
88
		}
89
		// replace orginal method with generated method using cache (lazy-load)
90
		jQuery.server = function(options){
91
			// clone cache object
92
			var myCache = jQuery.extend({}, objectCache);
93
			myCache.stack = [options];
94
			return myCache;
95
		}
96
		// returen result from new method (only done for first call)
97
		return jQuery.server(options);
98
	}
99
});
100
// toJSON by Mark Gibson
101
if (typeof $.toJSON == 'undefined') {
102
	(function ($) {
103
	    var m = {
104
	            '\b': '\\b',
105
	            '\t': '\\t',
106
	            '\n': '\\n',
107
	            '\f': '\\f',
108
	            '\r': '\\r',
109
	            '"' : '\\"',
110
	            '\\': '\\\\'
111
	        },
112
	        s = {
113
	            'array': function (x) {
114
	                var a = ['['], b, f, i, l = x.length, v;
115
	                for (i = 0; i < l; i += 1) {
116
	                    v = x[i];
117
	                    f = s[typeof v];
118
	                    if (f) {
119
	                        v = f(v);
120
	                        if (typeof v == 'string') {
121
	                            if (b) {
122
	                                a[a.length] = ',';
123
	                            }
124
	                            a[a.length] = v;
125
	                            b = true;
126
	                        }
127
	                    }
128
	                }
129
	                a[a.length] = ']';
130
	                return a.join('');
131
	            },
132
	            'boolean': function (x) {
133
	                return String(x);
134
	            },
135
	            'null': function (x) {
0 ignored issues
show
Unused Code introduced by
The parameter x is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
136
	                return "null";
137
	            },
138
	            'number': function (x) {
139
	                return isFinite(x) ? String(x) : 'null';
140
	            },
141
	            'object': function (x) {
142
	                if (x) {
143
	                    if (x instanceof Array) {
144
	                        return s.array(x);
145
	                    }
146
	                    var a = ['{'], b, f, i, v;
147
	                    for (i in x) {
148
	                        v = x[i];
149
	                        f = s[typeof v];
150
	                        if (f) {
151
	                            v = f(v);
152
	                            if (typeof v == 'string') {
153
	                                if (b) {
154
	                                    a[a.length] = ',';
155
	                                }
156
	                                a.push(s.string(i), ':', v);
157
	                                b = true;
158
	                            }
159
	                        }
160
	                    }
161
	                    a[a.length] = '}';
162
	                    return a.join('');
163
	                }
164
	                return 'null';
165
	            },
166
	            'string': function (x) {
167
	                if (/["\\\x00-\x1f]/.test(x)) {
168
	                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
169
	                        var c = m[b];
170
	                        if (c) {
171
	                            return c;
172
	                        }
173
	                        c = b.charCodeAt();
174
	                        return '\\u00' +
175
	                            Math.floor(c / 16).toString(16) +
176
	                            (c % 16).toString(16);
177
	                    });
178
	                }
179
	                return '"' + x + '"';
180
	            }
181
	        };
182
	
183
		$.toJSON = function(v) {
184
			var f = isNaN(v) ? s[typeof v] : s['number'];
185
			if (f) return f(v);
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if f is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
186
		};
187
		
188
		$.parseJSON = function(v, safe) {
189
            if (JSON)
190
                return JSON.parse(v);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
191
			if (safe === undefined)
192
                safe = $.parseJSON.safe;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
193
			if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
194
				return undefined;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
195
			return eval('('+v+')');
0 ignored issues
show
Security Performance introduced by
Calls to eval are slow and potentially dangerous, especially on untrusted code. Please consider whether there is another way to achieve your goal.
Loading history...
196
		};
197
		
198
		$.parseJSON.safe = false;
199
	
200
	})(jQuery);
201
}