Completed
Branch develop (c24f26)
by
unknown
26:13
created
htdocs/includes/restler/framework/Luracast/Restler/UI/Emmet.php 1 patch
Indentation   +355 added lines, -355 removed lines patch added patch discarded remove patch
@@ -12,367 +12,367 @@  discard block
 block discarded – undo
12 12
  */
13 13
 class Emmet
14 14
 {
15
-    const DELIMITERS = '.#*>+^[=" ]{$@-#}';
15
+	const DELIMITERS = '.#*>+^[=" ]{$@-#}';
16 16
 
17
-    /**
18
-     * Create the needed tag hierarchy from emmet string
19
-     *
20
-     * @param string       $string
21
-     *
22
-     * @param array|string $data
23
-     *
24
-     * @return array|T
25
-     */
26
-    public static function make($string, $data = null)
27
-    {
28
-        if (!strlen($string))
29
-            return array();
17
+	/**
18
+	 * Create the needed tag hierarchy from emmet string
19
+	 *
20
+	 * @param string       $string
21
+	 *
22
+	 * @param array|string $data
23
+	 *
24
+	 * @return array|T
25
+	 */
26
+	public static function make($string, $data = null)
27
+	{
28
+		if (!strlen($string))
29
+			return array();
30 30
 
31
-        $implicitTag =
32
-            function () use (& $tag) {
33
-                if (empty($tag->tag)) {
34
-                    switch ($tag->parent->tag) {
35
-                        case 'ul':
36
-                        case 'ol':
37
-                            $tag->tag = 'li';
38
-                            break;
39
-                        case 'em':
40
-                            $tag->tag = 'span';
41
-                            break;
42
-                        case 'table':
43
-                        case 'tbody':
44
-                        case 'thead':
45
-                        case 'tfoot':
46
-                            $tag->tag = 'tr';
47
-                            break;
48
-                        case 'tr':
49
-                            $tag->tag = 'td';
50
-                            break;
51
-                        case 'select':
52
-                        case 'optgroup':
53
-                            $tag->tag = 'option';
54
-                            break;
55
-                        default:
56
-                            $tag->tag = 'div';
57
-                    }
58
-                }
59
-            };
31
+		$implicitTag =
32
+			function () use (& $tag) {
33
+				if (empty($tag->tag)) {
34
+					switch ($tag->parent->tag) {
35
+						case 'ul':
36
+						case 'ol':
37
+							$tag->tag = 'li';
38
+							break;
39
+						case 'em':
40
+							$tag->tag = 'span';
41
+							break;
42
+						case 'table':
43
+						case 'tbody':
44
+						case 'thead':
45
+						case 'tfoot':
46
+							$tag->tag = 'tr';
47
+							break;
48
+						case 'tr':
49
+							$tag->tag = 'td';
50
+							break;
51
+						case 'select':
52
+						case 'optgroup':
53
+							$tag->tag = 'option';
54
+							break;
55
+						default:
56
+							$tag->tag = 'div';
57
+					}
58
+				}
59
+			};
60 60
 
61
-        $parseText =
62
-            function (
63
-                $text, $round, $total, $data, $delimiter = null
64
-            )
65
-            use (
66
-                & $tokens, & $tag
67
-            ) {
68
-                $digits = 0;
69
-                if ($delimiter == null)
70
-                    $delimiter = array(
71
-                        '.' => true,
72
-                        '#' => true,
73
-                        '*' => true,
74
-                        '>' => true,
75
-                        '+' => true,
76
-                        '^' => true,
77
-                        '[' => true,
78
-                        ']' => true,
79
-                        '=' => true,
80
-                    );
81
-                while (!empty($tokens) &&
82
-                    !isset($delimiter[$t = array_shift($tokens)])) {
83
-                    while ('$' === $t) {
84
-                        $digits++;
85
-                        $t = array_shift($tokens);
86
-                    }
87
-                    if ($digits) {
88
-                        $negative = false;
89
-                        $offset = 0;
90
-                        if ('@' == $t) {
91
-                            if ('-' == ($t = array_shift($tokens))) {
92
-                                $negative = true;
93
-                                if (is_numeric(reset($tokens))) {
94
-                                    $offset = array_shift($tokens);
95
-                                }
96
-                            } elseif (is_numeric($t)) {
97
-                                $offset = $t;
98
-                            } else {
99
-                                array_unshift($tokens, $t);
100
-                            }
101
-                        } elseif ('#' == ($h = array_shift($tokens))) {
102
-                            if (!empty($t)) {
103
-                                $data = Util::nestedValue($data, $t);
104
-                                if (is_null($data)) {
105
-                                    return null;
106
-                                }
107
-                            }
108
-                            if (is_numeric($data)) {
109
-                                $text .= sprintf("%0{$digits}d", (int)$data);
110
-                            } elseif (is_string($data)) {
111
-                                $text .= $data;
112
-                            }
113
-                            $digits = 0;
114
-                            continue;
115
-                        } else {
116
-                            array_unshift($tokens, $t, $h);
117
-                        }
118
-                        if ($negative) {
119
-                            $n = $total + 1 - $round + $offset;
120
-                        } else {
121
-                            $n = $round + $offset;
122
-                        }
123
-                        $text .= sprintf("%0{$digits}d", $n);
124
-                        $digits = 0;
125
-                    } else {
126
-                        $text .= $t;
127
-                    }
128
-                }
129
-                if (isset($t))
130
-                    array_unshift($tokens, $t);
131
-                return $text;
132
-            };
61
+		$parseText =
62
+			function (
63
+				$text, $round, $total, $data, $delimiter = null
64
+			)
65
+			use (
66
+				& $tokens, & $tag
67
+			) {
68
+				$digits = 0;
69
+				if ($delimiter == null)
70
+					$delimiter = array(
71
+						'.' => true,
72
+						'#' => true,
73
+						'*' => true,
74
+						'>' => true,
75
+						'+' => true,
76
+						'^' => true,
77
+						'[' => true,
78
+						']' => true,
79
+						'=' => true,
80
+					);
81
+				while (!empty($tokens) &&
82
+					!isset($delimiter[$t = array_shift($tokens)])) {
83
+					while ('$' === $t) {
84
+						$digits++;
85
+						$t = array_shift($tokens);
86
+					}
87
+					if ($digits) {
88
+						$negative = false;
89
+						$offset = 0;
90
+						if ('@' == $t) {
91
+							if ('-' == ($t = array_shift($tokens))) {
92
+								$negative = true;
93
+								if (is_numeric(reset($tokens))) {
94
+									$offset = array_shift($tokens);
95
+								}
96
+							} elseif (is_numeric($t)) {
97
+								$offset = $t;
98
+							} else {
99
+								array_unshift($tokens, $t);
100
+							}
101
+						} elseif ('#' == ($h = array_shift($tokens))) {
102
+							if (!empty($t)) {
103
+								$data = Util::nestedValue($data, $t);
104
+								if (is_null($data)) {
105
+									return null;
106
+								}
107
+							}
108
+							if (is_numeric($data)) {
109
+								$text .= sprintf("%0{$digits}d", (int)$data);
110
+							} elseif (is_string($data)) {
111
+								$text .= $data;
112
+							}
113
+							$digits = 0;
114
+							continue;
115
+						} else {
116
+							array_unshift($tokens, $t, $h);
117
+						}
118
+						if ($negative) {
119
+							$n = $total + 1 - $round + $offset;
120
+						} else {
121
+							$n = $round + $offset;
122
+						}
123
+						$text .= sprintf("%0{$digits}d", $n);
124
+						$digits = 0;
125
+					} else {
126
+						$text .= $t;
127
+					}
128
+				}
129
+				if (isset($t))
130
+					array_unshift($tokens, $t);
131
+				return $text;
132
+			};
133 133
 
134
-        $parseAttributes =
135
-            function (Callable $self, $round, $total, $data)
136
-            use (& $tokens, & $tag, $parseText) {
137
-                $a = $parseText(
138
-                    '', $round, $total, $data
139
-                );
140
-                if (is_null($a))
141
-                    return;
142
-                if ('=' == ($v = array_shift($tokens))) {
143
-                    //value
144
-                    if ('"' == ($v = array_shift($tokens))) {
145
-                        $text = '';
146
-                        $tag->$a($parseText(
147
-                            $text, $round, $total, $data,
148
-                            array('"' => true)
149
-                        ));
150
-                    } else {
151
-                        array_unshift($tokens, $v);
152
-                        $text = '';
153
-                        $tag->$a($parseText(
154
-                            $text, $round, $total, $data,
155
-                            array(' ' => true, ']' => true)
156
-                        ));
157
-                    }
158
-                    if (' ' == ($v = array_shift($tokens))) {
159
-                        $self($self, $round, $total, $data);
160
-                    }
161
-                } elseif (']' == $v) {
162
-                    //end
163
-                    $tag->$a('');
164
-                    return;
165
-                } elseif (' ' == $v) {
166
-                    $tag->$a('');
167
-                    $self($self, $round, $total, $data);
168
-                }
169
-            };
134
+		$parseAttributes =
135
+			function (Callable $self, $round, $total, $data)
136
+			use (& $tokens, & $tag, $parseText) {
137
+				$a = $parseText(
138
+					'', $round, $total, $data
139
+				);
140
+				if (is_null($a))
141
+					return;
142
+				if ('=' == ($v = array_shift($tokens))) {
143
+					//value
144
+					if ('"' == ($v = array_shift($tokens))) {
145
+						$text = '';
146
+						$tag->$a($parseText(
147
+							$text, $round, $total, $data,
148
+							array('"' => true)
149
+						));
150
+					} else {
151
+						array_unshift($tokens, $v);
152
+						$text = '';
153
+						$tag->$a($parseText(
154
+							$text, $round, $total, $data,
155
+							array(' ' => true, ']' => true)
156
+						));
157
+					}
158
+					if (' ' == ($v = array_shift($tokens))) {
159
+						$self($self, $round, $total, $data);
160
+					}
161
+				} elseif (']' == $v) {
162
+					//end
163
+					$tag->$a('');
164
+					return;
165
+				} elseif (' ' == $v) {
166
+					$tag->$a('');
167
+					$self($self, $round, $total, $data);
168
+				}
169
+			};
170 170
 
171
-        $tokens = static::tokenize($string);
172
-        $tag = new T(array_shift($tokens));
173
-        $parent = $root = new T;
171
+		$tokens = static::tokenize($string);
172
+		$tag = new T(array_shift($tokens));
173
+		$parent = $root = new T;
174 174
 
175
-        $parse =
176
-            function (
177
-                Callable $self, $round = 1, $total = 1
178
-            )
179
-            use (
180
-                & $tokens, & $parent, & $tag, & $data,
181
-                $parseAttributes, $implicitTag, $parseText
182
-            ) {
183
-                $offsetTokens = null;
184
-                $parent[] = $tag;
185
-                $isInChild = false;
186
-                while ($tokens) {
187
-                    switch (array_shift($tokens)) {
188
-                        //class
189
-                        case '.':
190
-                            $offsetTokens = array_values($tokens);
191
-                            array_unshift($offsetTokens, '.');
192
-                            $implicitTag();
193
-                            $e = array_filter(explode(' ', $tag->class));
194
-                            $e[] = $parseText('', $round, $total, $data);
195
-                            $tag->class(implode(' ', array_unique($e)));
196
-                            break;
197
-                        //id
198
-                        case '#':
199
-                            $offsetTokens = array_values($tokens);
200
-                            array_unshift($offsetTokens, '#');
201
-                            $implicitTag();
202
-                            $tag->id(
203
-                                $parseText(
204
-                                    array_shift($tokens), $round, $total, $data
205
-                                )
206
-                            );
207
-                            break;
208
-                        //attributes
209
-                        case '[':
210
-                            $offsetTokens = array_values($tokens);
211
-                            array_unshift($offsetTokens, '[');
212
-                            $implicitTag();
213
-                            $parseAttributes(
214
-                                $parseAttributes, $round, $total, $data
215
-                            );
216
-                            break;
217
-                        //child
218
-                        case '{':
219
-                            $text = '';
220
-                            $tag[] = $parseText(
221
-                                $text, $round, $total, $data, array('}' => true)
222
-                            );
223
-                            break;
224
-                        case '>':
225
-                            $isInChild = true;
226
-                            $offsetTokens = null;
227
-                            if ('{' == ($t = array_shift($tokens))) {
228
-                                array_unshift($tokens, $t);
229
-                                $child = new T();
230
-                                $tag[] = $child;
231
-                                $parent = $tag;
232
-                                $tag = $child;
233
-                            } elseif ('[' == $t) {
234
-                                array_unshift($tokens, $t);
235
-                            } else {
236
-                                $child = new T($t);
237
-                                $tag[] = $child;
238
-                                $parent = $tag;
239
-                                $tag = $child;
240
-                            }
241
-                            break;
242
-                        //sibling
243
-                        case '+':
244
-                            $offsetTokens = null;
245
-                            if (!$isInChild && $round != $total) {
246
-                                $tokens = array();
247
-                                break;
248
-                            }
249
-                            if ('{' == ($t = array_shift($tokens))) {
250
-                                $tag = $tag->parent;
251
-                                array_unshift($tokens, $t);
252
-                                break;
253
-                            } elseif ('[' == $t) {
254
-                                array_unshift($tokens, $t);
255
-                            } else {
256
-                                $child = new T($t);
257
-                                $tag = $tag->parent;
258
-                                $tag[] = $child;
259
-                                $tag = $child;
260
-                            }
261
-                            break;
262
-                        //sibling of parent
263
-                        case '^':
264
-                            if ($round != $total) {
265
-                                $tokens = array();
266
-                                break;
267
-                            }
268
-                            $tag = $tag->parent;
269
-                            if ($tag->parent)
270
-                                $tag = $tag->parent;
271
-                            while ('^' == ($t = array_shift($tokens))) {
272
-                                if ($tag->parent)
273
-                                    $tag = $tag->parent;
274
-                            }
275
-                            $child = new T($t);
276
-                            $tag[] = $child;
277
-                            $tag = $child;
278
-                            break;
279
-                        //clone
280
-                        case '*':
281
-                            $times = array_shift($tokens);
282
-                            $removeCount = 2;
283
-                            $delimiter = array(
284
-                                '.' => true,
285
-                                '#' => true,
286
-                                '*' => true,
287
-                                '>' => true,
288
-                                '+' => true,
289
-                                '^' => true,
290
-                                '[' => true,
291
-                                ']' => true,
292
-                                '=' => true,
293
-                            );
294
-                            if (!is_numeric($times)) {
295
-                                if (is_string($times)) {
296
-                                    if (!isset($delimiter[$times])) {
297
-                                        $data = Util::nestedValue($data, $times)
298
-                                            ? : $data;
299
-                                    } else {
300
-                                        array_unshift($tokens, $times);
301
-                                        $removeCount = 1;
302
-                                    }
303
-                                }
304
-                                $indexed = array_values($data);
305
-                                $times = is_array($data) && $indexed == $data
306
-                                    ? count($data) : 0;
307
-                            }
308
-                            $source = $tag;
309
-                            if (!empty($offsetTokens)) {
310
-                                if (false !== strpos($source->class, ' ')) {
311
-                                    $class = explode(' ', $source->class);
312
-                                    array_pop($class);
313
-                                    $class = implode(' ', $class);
314
-                                } else {
315
-                                    $class = null;
316
-                                }
317
-                                $tag->class($class);
318
-                                $star = array_search('*', $offsetTokens);
319
-                                array_splice($offsetTokens, $star, $removeCount);
320
-                                $remainingTokens = $offsetTokens;
321
-                            } else {
322
-                                $remainingTokens = $tokens;
323
-                            }
324
-                            $source->parent = null;
325
-                            $sourceData = $data;
326
-                            $currentParent = $parent;
327
-                            for ($i = 1; $i <= $times; $i++) {
328
-                                $tag = clone $source;
329
-                                $parent = $currentParent;
330
-                                $data = is_array($sourceData)
331
-                                && isset($sourceData[$i - 1])
332
-                                    ? $sourceData[$i - 1]
333
-                                    : @(string)$sourceData;
334
-                                $tokens = array_values($remainingTokens);
335
-                                $self($self, $i, $times);
336
-                            }
337
-                            $round = 1;
338
-                            $offsetTokens = null;
339
-                            $tag = $source;
340
-                            $tokens = array(); //$remainingTokens;
341
-                            break;
342
-                    }
343
-                }
344
-            };
345
-        $parse($parse);
346
-        return count($root) == 1 ? $root[0] : $root;
347
-    }
175
+		$parse =
176
+			function (
177
+				Callable $self, $round = 1, $total = 1
178
+			)
179
+			use (
180
+				& $tokens, & $parent, & $tag, & $data,
181
+				$parseAttributes, $implicitTag, $parseText
182
+			) {
183
+				$offsetTokens = null;
184
+				$parent[] = $tag;
185
+				$isInChild = false;
186
+				while ($tokens) {
187
+					switch (array_shift($tokens)) {
188
+						//class
189
+						case '.':
190
+							$offsetTokens = array_values($tokens);
191
+							array_unshift($offsetTokens, '.');
192
+							$implicitTag();
193
+							$e = array_filter(explode(' ', $tag->class));
194
+							$e[] = $parseText('', $round, $total, $data);
195
+							$tag->class(implode(' ', array_unique($e)));
196
+							break;
197
+						//id
198
+						case '#':
199
+							$offsetTokens = array_values($tokens);
200
+							array_unshift($offsetTokens, '#');
201
+							$implicitTag();
202
+							$tag->id(
203
+								$parseText(
204
+									array_shift($tokens), $round, $total, $data
205
+								)
206
+							);
207
+							break;
208
+						//attributes
209
+						case '[':
210
+							$offsetTokens = array_values($tokens);
211
+							array_unshift($offsetTokens, '[');
212
+							$implicitTag();
213
+							$parseAttributes(
214
+								$parseAttributes, $round, $total, $data
215
+							);
216
+							break;
217
+						//child
218
+						case '{':
219
+							$text = '';
220
+							$tag[] = $parseText(
221
+								$text, $round, $total, $data, array('}' => true)
222
+							);
223
+							break;
224
+						case '>':
225
+							$isInChild = true;
226
+							$offsetTokens = null;
227
+							if ('{' == ($t = array_shift($tokens))) {
228
+								array_unshift($tokens, $t);
229
+								$child = new T();
230
+								$tag[] = $child;
231
+								$parent = $tag;
232
+								$tag = $child;
233
+							} elseif ('[' == $t) {
234
+								array_unshift($tokens, $t);
235
+							} else {
236
+								$child = new T($t);
237
+								$tag[] = $child;
238
+								$parent = $tag;
239
+								$tag = $child;
240
+							}
241
+							break;
242
+						//sibling
243
+						case '+':
244
+							$offsetTokens = null;
245
+							if (!$isInChild && $round != $total) {
246
+								$tokens = array();
247
+								break;
248
+							}
249
+							if ('{' == ($t = array_shift($tokens))) {
250
+								$tag = $tag->parent;
251
+								array_unshift($tokens, $t);
252
+								break;
253
+							} elseif ('[' == $t) {
254
+								array_unshift($tokens, $t);
255
+							} else {
256
+								$child = new T($t);
257
+								$tag = $tag->parent;
258
+								$tag[] = $child;
259
+								$tag = $child;
260
+							}
261
+							break;
262
+						//sibling of parent
263
+						case '^':
264
+							if ($round != $total) {
265
+								$tokens = array();
266
+								break;
267
+							}
268
+							$tag = $tag->parent;
269
+							if ($tag->parent)
270
+								$tag = $tag->parent;
271
+							while ('^' == ($t = array_shift($tokens))) {
272
+								if ($tag->parent)
273
+									$tag = $tag->parent;
274
+							}
275
+							$child = new T($t);
276
+							$tag[] = $child;
277
+							$tag = $child;
278
+							break;
279
+						//clone
280
+						case '*':
281
+							$times = array_shift($tokens);
282
+							$removeCount = 2;
283
+							$delimiter = array(
284
+								'.' => true,
285
+								'#' => true,
286
+								'*' => true,
287
+								'>' => true,
288
+								'+' => true,
289
+								'^' => true,
290
+								'[' => true,
291
+								']' => true,
292
+								'=' => true,
293
+							);
294
+							if (!is_numeric($times)) {
295
+								if (is_string($times)) {
296
+									if (!isset($delimiter[$times])) {
297
+										$data = Util::nestedValue($data, $times)
298
+											? : $data;
299
+									} else {
300
+										array_unshift($tokens, $times);
301
+										$removeCount = 1;
302
+									}
303
+								}
304
+								$indexed = array_values($data);
305
+								$times = is_array($data) && $indexed == $data
306
+									? count($data) : 0;
307
+							}
308
+							$source = $tag;
309
+							if (!empty($offsetTokens)) {
310
+								if (false !== strpos($source->class, ' ')) {
311
+									$class = explode(' ', $source->class);
312
+									array_pop($class);
313
+									$class = implode(' ', $class);
314
+								} else {
315
+									$class = null;
316
+								}
317
+								$tag->class($class);
318
+								$star = array_search('*', $offsetTokens);
319
+								array_splice($offsetTokens, $star, $removeCount);
320
+								$remainingTokens = $offsetTokens;
321
+							} else {
322
+								$remainingTokens = $tokens;
323
+							}
324
+							$source->parent = null;
325
+							$sourceData = $data;
326
+							$currentParent = $parent;
327
+							for ($i = 1; $i <= $times; $i++) {
328
+								$tag = clone $source;
329
+								$parent = $currentParent;
330
+								$data = is_array($sourceData)
331
+								&& isset($sourceData[$i - 1])
332
+									? $sourceData[$i - 1]
333
+									: @(string)$sourceData;
334
+								$tokens = array_values($remainingTokens);
335
+								$self($self, $i, $times);
336
+							}
337
+							$round = 1;
338
+							$offsetTokens = null;
339
+							$tag = $source;
340
+							$tokens = array(); //$remainingTokens;
341
+							break;
342
+					}
343
+				}
344
+			};
345
+		$parse($parse);
346
+		return count($root) == 1 ? $root[0] : $root;
347
+	}
348 348
 
349
-    public static function tokenize($string)
350
-    {
351
-        $r = array();
352
-        $f = strtok($string, static::DELIMITERS);
353
-        $pos = 0;
354
-        do {
355
-            $start = $pos;
356
-            $pos = strpos($string, $f, $start);
357
-            $tokens = array();
358
-            for ($i = $start; $i < $pos; $i++) {
359
-                $token = $string[$i];
360
-                if (('#' == $token || '.' == $token) &&
361
-                    (!empty($tokens) || $i == 0)
362
-                ) {
363
-                    $r[] = '';
364
-                }
365
-                $r[] = $tokens[] = $token;
366
-            }
367
-            $pos += strlen($f);
368
-            $r[] = $f;
369
-        } while (false != ($f = strtok(static::DELIMITERS)));
370
-        for ($i = $pos; $i < strlen($string); $i++) {
371
-            $token = $string[$i];
372
-            $r[] = $tokens[] = $token;
373
-        }
374
-        return $r;
375
-        /* sample output produced by ".row*3>.col*3"
349
+	public static function tokenize($string)
350
+	{
351
+		$r = array();
352
+		$f = strtok($string, static::DELIMITERS);
353
+		$pos = 0;
354
+		do {
355
+			$start = $pos;
356
+			$pos = strpos($string, $f, $start);
357
+			$tokens = array();
358
+			for ($i = $start; $i < $pos; $i++) {
359
+				$token = $string[$i];
360
+				if (('#' == $token || '.' == $token) &&
361
+					(!empty($tokens) || $i == 0)
362
+				) {
363
+					$r[] = '';
364
+				}
365
+				$r[] = $tokens[] = $token;
366
+			}
367
+			$pos += strlen($f);
368
+			$r[] = $f;
369
+		} while (false != ($f = strtok(static::DELIMITERS)));
370
+		for ($i = $pos; $i < strlen($string); $i++) {
371
+			$token = $string[$i];
372
+			$r[] = $tokens[] = $token;
373
+		}
374
+		return $r;
375
+		/* sample output produced by ".row*3>.col*3"
376 376
         [0] => div
377 377
         [1] => .
378 378
         [2] => row
@@ -385,5 +385,5 @@  discard block
 block discarded – undo
385 385
         [9] => *
386 386
         [10] => 4
387 387
          */
388
-    }
388
+	}
389 389
 }
390 390
\ No newline at end of file
Please login to merge, or discard this patch.
htdocs/includes/restler/framework/Luracast/Restler/Filter/RateLimit.php 1 patch
Indentation   +144 added lines, -144 removed lines patch added patch discarded remove patch
@@ -19,160 +19,160 @@
 block discarded – undo
19 19
  */
20 20
 class RateLimit implements iFilter, iUseAuthentication
21 21
 {
22
-    /**
23
-     * @var \Luracast\Restler\Restler;
24
-     */
25
-    public $restler;
26
-    /**
27
-     * @var int
28
-     */
29
-    public static $usagePerUnit = 1200;
30
-    /**
31
-     * @var int
32
-     */
33
-    public static $authenticatedUsagePerUnit = 5000;
34
-    /**
35
-     * @var string
36
-     */
37
-    public static $unit = 'hour';
38
-    /**
39
-     * @var string group the current api belongs to
40
-     */
41
-    public static $group = 'common';
22
+	/**
23
+	 * @var \Luracast\Restler\Restler;
24
+	 */
25
+	public $restler;
26
+	/**
27
+	 * @var int
28
+	 */
29
+	public static $usagePerUnit = 1200;
30
+	/**
31
+	 * @var int
32
+	 */
33
+	public static $authenticatedUsagePerUnit = 5000;
34
+	/**
35
+	 * @var string
36
+	 */
37
+	public static $unit = 'hour';
38
+	/**
39
+	 * @var string group the current api belongs to
40
+	 */
41
+	public static $group = 'common';
42 42
 
43
-    protected static $units = array(
44
-        'second' => 1,
45
-        'minute' => 60,
46
-        'hour' => 3600, // 60*60 seconds
47
-        'day' => 86400, // 60*60*24 seconds
48
-        'week' => 604800, // 60*60*24*7 seconds
49
-        'month' => 2592000, // 60*60*24*30 seconds
50
-    );
43
+	protected static $units = array(
44
+		'second' => 1,
45
+		'minute' => 60,
46
+		'hour' => 3600, // 60*60 seconds
47
+		'day' => 86400, // 60*60*24 seconds
48
+		'week' => 604800, // 60*60*24*7 seconds
49
+		'month' => 2592000, // 60*60*24*30 seconds
50
+	);
51 51
 
52
-    /**
53
-     * @var array all paths beginning with any of the following will be excluded
54
-     * from documentation
55
-     */
56
-    public static $excludedPaths = array('explorer');
52
+	/**
53
+	 * @var array all paths beginning with any of the following will be excluded
54
+	 * from documentation
55
+	 */
56
+	public static $excludedPaths = array('explorer');
57 57
 
58 58
 
59
-    /**
60
-     * @param string $unit
61
-     * @param int    $usagePerUnit
62
-     * @param int    $authenticatedUsagePerUnit set it to false to give unlimited access
63
-     *
64
-     * @throws \InvalidArgumentException
65
-     * @return void
66
-     */
67
-    public static function setLimit(
68
-        $unit, $usagePerUnit, $authenticatedUsagePerUnit = null
69
-    )
70
-    {
71
-        static::$unit = $unit;
72
-        static::$usagePerUnit = $usagePerUnit;
73
-        static::$authenticatedUsagePerUnit =
74
-            is_null($authenticatedUsagePerUnit) ? $usagePerUnit : $authenticatedUsagePerUnit;
75
-    }
59
+	/**
60
+	 * @param string $unit
61
+	 * @param int    $usagePerUnit
62
+	 * @param int    $authenticatedUsagePerUnit set it to false to give unlimited access
63
+	 *
64
+	 * @throws \InvalidArgumentException
65
+	 * @return void
66
+	 */
67
+	public static function setLimit(
68
+		$unit, $usagePerUnit, $authenticatedUsagePerUnit = null
69
+	)
70
+	{
71
+		static::$unit = $unit;
72
+		static::$usagePerUnit = $usagePerUnit;
73
+		static::$authenticatedUsagePerUnit =
74
+			is_null($authenticatedUsagePerUnit) ? $usagePerUnit : $authenticatedUsagePerUnit;
75
+	}
76 76
 
77
-    public function __isAllowed()
78
-    {
79
-        if (static::$authenticatedUsagePerUnit
80
-            == static::$usagePerUnit
81
-        ) return $this->check();
82
-        return null;
83
-    }
77
+	public function __isAllowed()
78
+	{
79
+		if (static::$authenticatedUsagePerUnit
80
+			== static::$usagePerUnit
81
+		) return $this->check();
82
+		return null;
83
+	}
84 84
 
85
-    public function __setAuthenticationStatus($isAuthenticated = false)
86
-    {
87
-        header('X-Auth-Status: ' . ($isAuthenticated ? 'true' : 'false'));
88
-        $this->check($isAuthenticated);
89
-    }
85
+	public function __setAuthenticationStatus($isAuthenticated = false)
86
+	{
87
+		header('X-Auth-Status: ' . ($isAuthenticated ? 'true' : 'false'));
88
+		$this->check($isAuthenticated);
89
+	}
90 90
 
91
-    private static function validate($unit)
92
-    {
93
-        if (!isset(static::$units[$unit]))
94
-            throw new \InvalidArgumentException(
95
-                'Rate Limit time unit should be '
96
-                . implode('|', array_keys(static::$units)) . '.'
97
-            );
98
-    }
91
+	private static function validate($unit)
92
+	{
93
+		if (!isset(static::$units[$unit]))
94
+			throw new \InvalidArgumentException(
95
+				'Rate Limit time unit should be '
96
+				. implode('|', array_keys(static::$units)) . '.'
97
+			);
98
+	}
99 99
 
100
-    private function check($isAuthenticated = false)
101
-    {
102
-        $path = $this->restler->url;
103
-        foreach (static::$excludedPaths as $exclude) {
104
-            if (empty($exclude) && empty($path)) {
105
-                return true;
106
-            } elseif (0 === strpos($path, $exclude)) {
107
-                return true;
108
-            }
109
-        }
110
-        static::validate(static::$unit);
111
-        $timeUnit = static::$units[static::$unit];
112
-        $maxPerUnit = $isAuthenticated
113
-            ? static::$authenticatedUsagePerUnit
114
-            : static::$usagePerUnit;
115
-        if ($maxPerUnit) {
116
-            $user = Defaults::$userIdentifierClass;
117
-            if (!method_exists($user, 'getUniqueIdentifier')) {
118
-                throw new \UnexpectedValueException('`Defaults::$userIdentifierClass` must implement `iIdentifyUser` interface');
119
-            }
120
-            $id = "RateLimit_" . $maxPerUnit . '_per_' . static::$unit
121
-                . '_for_' . static::$group
122
-                . '_' . $user::getUniqueIdentifier();
123
-            $lastRequest = $this->restler->cache->get($id, true)
124
-                ? : array('time' => 0, 'used' => 0);
125
-            $time = $lastRequest['time'];
126
-            $diff = time() - $time; # in seconds
127
-            $used = $lastRequest['used'];
100
+	private function check($isAuthenticated = false)
101
+	{
102
+		$path = $this->restler->url;
103
+		foreach (static::$excludedPaths as $exclude) {
104
+			if (empty($exclude) && empty($path)) {
105
+				return true;
106
+			} elseif (0 === strpos($path, $exclude)) {
107
+				return true;
108
+			}
109
+		}
110
+		static::validate(static::$unit);
111
+		$timeUnit = static::$units[static::$unit];
112
+		$maxPerUnit = $isAuthenticated
113
+			? static::$authenticatedUsagePerUnit
114
+			: static::$usagePerUnit;
115
+		if ($maxPerUnit) {
116
+			$user = Defaults::$userIdentifierClass;
117
+			if (!method_exists($user, 'getUniqueIdentifier')) {
118
+				throw new \UnexpectedValueException('`Defaults::$userIdentifierClass` must implement `iIdentifyUser` interface');
119
+			}
120
+			$id = "RateLimit_" . $maxPerUnit . '_per_' . static::$unit
121
+				. '_for_' . static::$group
122
+				. '_' . $user::getUniqueIdentifier();
123
+			$lastRequest = $this->restler->cache->get($id, true)
124
+				? : array('time' => 0, 'used' => 0);
125
+			$time = $lastRequest['time'];
126
+			$diff = time() - $time; # in seconds
127
+			$used = $lastRequest['used'];
128 128
 
129
-            header("X-RateLimit-Limit: $maxPerUnit per " . static::$unit);
130
-            if ($diff >= $timeUnit) {
131
-                $used = 1;
132
-                $time = time();
133
-            } elseif ($used >= $maxPerUnit) {
134
-                header("X-RateLimit-Remaining: 0");
135
-                $wait = $timeUnit - $diff;
136
-                sleep(1);
137
-                throw new RestException(429,
138
-                    'Rate limit of ' . $maxPerUnit . ' request' .
139
-                    ($maxPerUnit > 1 ? 's' : '') . ' per '
140
-                    . static::$unit . ' exceeded. Please wait for '
141
-                    . static::duration($wait) . '.'
142
-                );
143
-            } else {
144
-                $used++;
145
-            }
146
-            $remainingPerUnit = $maxPerUnit - $used;
147
-            header("X-RateLimit-Remaining: $remainingPerUnit");
148
-            $this->restler->cache->set($id,
149
-                array('time' => $time, 'used' => $used));
150
-        }
151
-        return true;
152
-    }
129
+			header("X-RateLimit-Limit: $maxPerUnit per " . static::$unit);
130
+			if ($diff >= $timeUnit) {
131
+				$used = 1;
132
+				$time = time();
133
+			} elseif ($used >= $maxPerUnit) {
134
+				header("X-RateLimit-Remaining: 0");
135
+				$wait = $timeUnit - $diff;
136
+				sleep(1);
137
+				throw new RestException(429,
138
+					'Rate limit of ' . $maxPerUnit . ' request' .
139
+					($maxPerUnit > 1 ? 's' : '') . ' per '
140
+					. static::$unit . ' exceeded. Please wait for '
141
+					. static::duration($wait) . '.'
142
+				);
143
+			} else {
144
+				$used++;
145
+			}
146
+			$remainingPerUnit = $maxPerUnit - $used;
147
+			header("X-RateLimit-Remaining: $remainingPerUnit");
148
+			$this->restler->cache->set($id,
149
+				array('time' => $time, 'used' => $used));
150
+		}
151
+		return true;
152
+	}
153 153
 
154
-    private function duration($secs)
155
-    {
156
-        $units = array(
157
-            'week' => (int)($secs / 86400 / 7),
158
-            'day' => $secs / 86400 % 7,
159
-            'hour' => $secs / 3600 % 24,
160
-            'minute' => $secs / 60 % 60,
161
-            'second' => $secs % 60);
154
+	private function duration($secs)
155
+	{
156
+		$units = array(
157
+			'week' => (int)($secs / 86400 / 7),
158
+			'day' => $secs / 86400 % 7,
159
+			'hour' => $secs / 3600 % 24,
160
+			'minute' => $secs / 60 % 60,
161
+			'second' => $secs % 60);
162 162
 
163
-        $ret = array();
163
+		$ret = array();
164 164
 
165
-        //$unit = 'days';
166
-        foreach ($units as $k => $v) {
167
-            if ($v > 0) {
168
-                $ret[] = $v > 1 ? "$v {$k}s" : "$v $k";
169
-                //$unit = $k;
170
-            }
171
-        }
172
-        $i = count($ret) - 1;
173
-        if ($i) {
174
-            $ret[$i] = 'and ' . $ret[$i];
175
-        }
176
-        return implode(' ', $ret); //." $unit.";
177
-    }
165
+		//$unit = 'days';
166
+		foreach ($units as $k => $v) {
167
+			if ($v > 0) {
168
+				$ret[] = $v > 1 ? "$v {$k}s" : "$v $k";
169
+				//$unit = $k;
170
+			}
171
+		}
172
+		$i = count($ret) - 1;
173
+		if ($i) {
174
+			$ret[$i] = 'and ' . $ret[$i];
175
+		}
176
+		return implode(' ', $ret); //." $unit.";
177
+	}
178 178
 }
179 179
\ No newline at end of file
Please login to merge, or discard this patch.
htdocs/includes/restler/framework/Luracast/Restler/Format/AmfFormat.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -21,28 +21,28 @@
 block discarded – undo
21 21
  */
22 22
 class AmfFormat extends DependentFormat
23 23
 {
24
-    const MIME = 'application/x-amf';
25
-    const EXTENSION = 'amf';
24
+	const MIME = 'application/x-amf';
25
+	const EXTENSION = 'amf';
26 26
 
27
-    const PACKAGE_NAME = 'zendframework/zendamf:dev-master';
28
-    const EXTERNAL_CLASS = 'ZendAmf\\Parser\\Amf3\\Deserializer';
27
+	const PACKAGE_NAME = 'zendframework/zendamf:dev-master';
28
+	const EXTERNAL_CLASS = 'ZendAmf\\Parser\\Amf3\\Deserializer';
29 29
 
30
-    public function encode($data, $humanReadable = false)
31
-    {
30
+	public function encode($data, $humanReadable = false)
31
+	{
32 32
 
33
-        $stream = new OutputStream();
34
-        $serializer = new Serializer($stream);
35
-        $serializer->writeTypeMarker($data);
33
+		$stream = new OutputStream();
34
+		$serializer = new Serializer($stream);
35
+		$serializer->writeTypeMarker($data);
36 36
 
37
-        return $stream->getStream();
38
-    }
37
+		return $stream->getStream();
38
+	}
39 39
 
40
-    public function decode($data)
41
-    {
42
-        $stream = new InputStream(substr($data, 1));
43
-        $deserializer = new Deserializer($stream);
40
+	public function decode($data)
41
+	{
42
+		$stream = new InputStream(substr($data, 1));
43
+		$deserializer = new Deserializer($stream);
44 44
 
45
-        return $deserializer->readTypeMarker();
46
-    }
45
+		return $deserializer->readTypeMarker();
46
+	}
47 47
 }
48 48
 
Please login to merge, or discard this patch.
htdocs/includes/restler/framework/Luracast/Restler/Format/Format.php 1 patch
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -14,127 +14,127 @@
 block discarded – undo
14 14
  */
15 15
 abstract class Format implements iFormat
16 16
 {
17
-    /**
18
-     * override in the extending class
19
-     */
20
-    const MIME = 'text/plain';
21
-    /**
22
-     * override in the extending class
23
-     */
24
-    const EXTENSION = 'txt';
17
+	/**
18
+	 * override in the extending class
19
+	 */
20
+	const MIME = 'text/plain';
21
+	/**
22
+	 * override in the extending class
23
+	 */
24
+	const EXTENSION = 'txt';
25 25
 
26
-    /**
27
-     * @var string charset encoding defaults to UTF8
28
-     */
29
-    protected $charset='utf-8';
26
+	/**
27
+	 * @var string charset encoding defaults to UTF8
28
+	 */
29
+	protected $charset='utf-8';
30 30
 
31
-    /**
32
-     * Injected at runtime
33
-     *
34
-     * @var \Luracast\Restler\Restler
35
-     */
36
-    public $restler;
31
+	/**
32
+	 * Injected at runtime
33
+	 *
34
+	 * @var \Luracast\Restler\Restler
35
+	 */
36
+	public $restler;
37 37
 
38
-    /**
39
-     * Get MIME type => Extension mappings as an associative array
40
-     *
41
-     * @return array list of mime strings for the format
42
-     * @example array('application/json'=>'json');
43
-     */
44
-    public function getMIMEMap()
45
-    {
46
-        return array(
47
-            static::MIME =>  static::EXTENSION
48
-        );
49
-    }
38
+	/**
39
+	 * Get MIME type => Extension mappings as an associative array
40
+	 *
41
+	 * @return array list of mime strings for the format
42
+	 * @example array('application/json'=>'json');
43
+	 */
44
+	public function getMIMEMap()
45
+	{
46
+		return array(
47
+			static::MIME =>  static::EXTENSION
48
+		);
49
+	}
50 50
 
51
-    /**
52
-     * Set the selected MIME type
53
-     *
54
-     * @param string $mime
55
-     *            MIME type
56
-     */
57
-    public function setMIME($mime)
58
-    {
59
-        //do nothing
60
-    }
51
+	/**
52
+	 * Set the selected MIME type
53
+	 *
54
+	 * @param string $mime
55
+	 *            MIME type
56
+	 */
57
+	public function setMIME($mime)
58
+	{
59
+		//do nothing
60
+	}
61 61
 
62
-    /**
63
-     * Content-Type field of the HTTP header can send a charset
64
-     * parameter in the HTTP header to specify the character
65
-     * encoding of the document.
66
-     * This information is passed
67
-     * here so that Format class can encode data accordingly
68
-     * Format class may choose to ignore this and use its
69
-     * default character set.
70
-     *
71
-     * @param string $charset
72
-     *            Example utf-8
73
-     */
74
-    public function setCharset($charset)
75
-    {
76
-        $this->charset = $charset;
77
-    }
62
+	/**
63
+	 * Content-Type field of the HTTP header can send a charset
64
+	 * parameter in the HTTP header to specify the character
65
+	 * encoding of the document.
66
+	 * This information is passed
67
+	 * here so that Format class can encode data accordingly
68
+	 * Format class may choose to ignore this and use its
69
+	 * default character set.
70
+	 *
71
+	 * @param string $charset
72
+	 *            Example utf-8
73
+	 */
74
+	public function setCharset($charset)
75
+	{
76
+		$this->charset = $charset;
77
+	}
78 78
 
79
-    /**
80
-     * Content-Type accepted by the Format class
81
-     *
82
-     * @return string $charset Example utf-8
83
-     */
84
-    public function getCharset()
85
-    {
86
-        return $this->charset;
87
-    }
79
+	/**
80
+	 * Content-Type accepted by the Format class
81
+	 *
82
+	 * @return string $charset Example utf-8
83
+	 */
84
+	public function getCharset()
85
+	{
86
+		return $this->charset;
87
+	}
88 88
 
89
-    /**
90
-     * Get selected MIME type
91
-     */
92
-    public function getMIME()
93
-    {
94
-        return static::MIME;
95
-    }
89
+	/**
90
+	 * Get selected MIME type
91
+	 */
92
+	public function getMIME()
93
+	{
94
+		return static::MIME;
95
+	}
96 96
 
97
-    /**
98
-     * Set the selected file extension
99
-     *
100
-     * @param string $extension
101
-     *            file extension
102
-     */
103
-    public function setExtension($extension)
104
-    {
105
-        //do nothing;
106
-    }
97
+	/**
98
+	 * Set the selected file extension
99
+	 *
100
+	 * @param string $extension
101
+	 *            file extension
102
+	 */
103
+	public function setExtension($extension)
104
+	{
105
+		//do nothing;
106
+	}
107 107
 
108
-    /**
109
-     * Get the selected file extension
110
-     *
111
-     * @return string file extension
112
-     */
113
-    public function getExtension()
114
-    {
115
-        return static::EXTENSION;
116
-    }
108
+	/**
109
+	 * Get the selected file extension
110
+	 *
111
+	 * @return string file extension
112
+	 */
113
+	public function getExtension()
114
+	{
115
+		return static::EXTENSION;
116
+	}
117 117
 
118
-    /**
119
-     * @return boolean is parsing the request supported?
120
-     */
121
-    public function isReadable()
122
-    {
123
-        return true;
124
-    }
118
+	/**
119
+	 * @return boolean is parsing the request supported?
120
+	 */
121
+	public function isReadable()
122
+	{
123
+		return true;
124
+	}
125 125
 
126
-    /**
127
-     * @return boolean is composing response supported?
128
-     */
129
-    public function isWritable()
130
-    {
131
-        return true;
132
-    }
126
+	/**
127
+	 * @return boolean is composing response supported?
128
+	 */
129
+	public function isWritable()
130
+	{
131
+		return true;
132
+	}
133 133
 
134
-    public function __toString()
135
-    {
136
-        return $this->getExtension();
137
-    }
134
+	public function __toString()
135
+	{
136
+		return $this->getExtension();
137
+	}
138 138
 
139 139
 }
140 140
 
Please login to merge, or discard this patch.
htdocs/includes/restler/framework/Luracast/Restler/Format/CsvFormat.php 1 patch
Indentation   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -20,162 +20,162 @@
 block discarded – undo
20 20
 class CsvFormat extends Format implements iDecodeStream
21 21
 {
22 22
 
23
-    const MIME = 'text/csv';
24
-    const EXTENSION = 'csv';
25
-    public static $delimiter = ',';
26
-    public static $enclosure = '"';
27
-    public static $escape = '\\';
28
-    public static $haveHeaders = null;
29
-
30
-    /**
31
-     * Encode the given data in the csv format
32
-     *
33
-     * @param array   $data
34
-     *            resulting data that needs to
35
-     *            be encoded in the given format
36
-     * @param boolean $humanReadable
37
-     *            set to TRUE when restler
38
-     *            is not running in production mode. Formatter has to
39
-     *            make the encoded output more human readable
40
-     *
41
-     * @return string encoded string
42
-     *
43
-     * @throws RestException 500 on unsupported data
44
-     */
45
-    public function encode($data, $humanReadable = false)
46
-    {
47
-        $char = Obj::$separatorChar;
48
-        Obj::$separatorChar = false;
49
-        $data = Obj::toArray($data);
50
-        Obj::$separatorChar = $char;
51
-        if (is_array($data) && array_values($data) == $data) {
52
-            //if indexed array
53
-            $lines = array();
54
-            $row = array_shift($data);
55
-            if (array_values($row) != $row) {
56
-                $lines[] = static::putRow(array_keys($row));
57
-            }
58
-            $lines[] = static::putRow(array_values($row));
59
-            foreach ($data as $row) {
60
-                $lines[] = static::putRow(array_values($row));
61
-            }
62
-            return implode(PHP_EOL, $lines) . PHP_EOL;
63
-        }
64
-        throw new RestException(
65
-            500,
66
-            'Unsupported data for ' . strtoupper(static::EXTENSION) . ' format'
67
-        );
68
-    }
69
-
70
-    protected static function putRow($data)
71
-    {
72
-        $fp = fopen('php://temp', 'r+');
73
-        fputcsv($fp, $data, static::$delimiter, static::$enclosure);
74
-        rewind($fp);
75
-        $data = fread($fp, 1048576);
76
-        fclose($fp);
77
-        return rtrim($data, PHP_EOL);
78
-    }
79
-
80
-    /**
81
-     * Decode the given data from the csv format
82
-     *
83
-     * @param string $data
84
-     *            data sent from client to
85
-     *            the api in the given format.
86
-     *
87
-     * @return array associative array of the parsed data
88
-     */
89
-    public function decode($data)
90
-    {
91
-        $decoded = array();
92
-
93
-        if (empty($data)) {
94
-            return $decoded;
95
-        }
96
-
97
-        $lines = array_filter(explode(PHP_EOL, $data));
98
-
99
-        $keys = false;
100
-        $row = static::getRow(array_shift($lines));
101
-
102
-        if (is_null(static::$haveHeaders)) {
103
-            //try to guess with the given data
104
-            static::$haveHeaders = !count(array_filter($row, 'is_numeric'));
105
-        }
106
-
107
-        static::$haveHeaders ? $keys = $row : $decoded[] = $row;
108
-
109
-        while (($row = static::getRow(array_shift($lines), $keys)) !== FALSE)
110
-            $decoded [] = $row;
111
-
112
-        $char = Obj::$separatorChar;
113
-        Obj::$separatorChar = false;
114
-        $decoded = Obj::toArray($decoded);
115
-        Obj::$separatorChar = $char;
116
-        return $decoded;
117
-    }
118
-
119
-    protected static function getRow($data, $keys = false)
120
-    {
121
-        if (empty($data)) {
122
-            return false;
123
-        }
124
-        $line = str_getcsv(
125
-            $data,
126
-            static::$delimiter,
127
-            static::$enclosure,
128
-            static::$escape
129
-        );
130
-
131
-        $row = array();
132
-        foreach ($line as $key => $value) {
133
-            if (is_numeric($value))
134
-                $value = floatval($value);
135
-            if ($keys) {
136
-                if (isset($keys [$key]))
137
-                    $row [$keys [$key]] = $value;
138
-            } else {
139
-                $row [$key] = $value;
140
-            }
141
-        }
142
-        if ($keys) {
143
-            for ($i = count($row); $i < count($keys); $i++) {
144
-                $row[$keys[$i]] = null;
145
-            }
146
-        }
147
-        return $row;
148
-    }
149
-
150
-    /**
151
-     * Decode the given data stream
152
-     *
153
-     * @param string $stream A stream resource with data
154
-     *                       sent from client to the api
155
-     *                       in the given format.
156
-     *
157
-     * @return array associative array of the parsed data
158
-     */
159
-    public function decodeStream($stream)
160
-    {
161
-        $decoded = array();
162
-
163
-        $keys = false;
164
-        $row = static::getRow(stream_get_line($stream, 0, PHP_EOL));
165
-        if (is_null(static::$haveHeaders)) {
166
-            //try to guess with the given data
167
-            static::$haveHeaders = !count(array_filter($row, 'is_numeric'));
168
-        }
169
-
170
-        static::$haveHeaders ? $keys = $row : $decoded[] = $row;
171
-
172
-        while (($row = static::getRow(stream_get_line($stream, 0, PHP_EOL), $keys)) !== FALSE)
173
-            $decoded [] = $row;
174
-
175
-        $char = Obj::$separatorChar;
176
-        Obj::$separatorChar = false;
177
-        $decoded = Obj::toArray($decoded);
178
-        Obj::$separatorChar = $char;
179
-        return $decoded;
180
-    }
23
+	const MIME = 'text/csv';
24
+	const EXTENSION = 'csv';
25
+	public static $delimiter = ',';
26
+	public static $enclosure = '"';
27
+	public static $escape = '\\';
28
+	public static $haveHeaders = null;
29
+
30
+	/**
31
+	 * Encode the given data in the csv format
32
+	 *
33
+	 * @param array   $data
34
+	 *            resulting data that needs to
35
+	 *            be encoded in the given format
36
+	 * @param boolean $humanReadable
37
+	 *            set to TRUE when restler
38
+	 *            is not running in production mode. Formatter has to
39
+	 *            make the encoded output more human readable
40
+	 *
41
+	 * @return string encoded string
42
+	 *
43
+	 * @throws RestException 500 on unsupported data
44
+	 */
45
+	public function encode($data, $humanReadable = false)
46
+	{
47
+		$char = Obj::$separatorChar;
48
+		Obj::$separatorChar = false;
49
+		$data = Obj::toArray($data);
50
+		Obj::$separatorChar = $char;
51
+		if (is_array($data) && array_values($data) == $data) {
52
+			//if indexed array
53
+			$lines = array();
54
+			$row = array_shift($data);
55
+			if (array_values($row) != $row) {
56
+				$lines[] = static::putRow(array_keys($row));
57
+			}
58
+			$lines[] = static::putRow(array_values($row));
59
+			foreach ($data as $row) {
60
+				$lines[] = static::putRow(array_values($row));
61
+			}
62
+			return implode(PHP_EOL, $lines) . PHP_EOL;
63
+		}
64
+		throw new RestException(
65
+			500,
66
+			'Unsupported data for ' . strtoupper(static::EXTENSION) . ' format'
67
+		);
68
+	}
69
+
70
+	protected static function putRow($data)
71
+	{
72
+		$fp = fopen('php://temp', 'r+');
73
+		fputcsv($fp, $data, static::$delimiter, static::$enclosure);
74
+		rewind($fp);
75
+		$data = fread($fp, 1048576);
76
+		fclose($fp);
77
+		return rtrim($data, PHP_EOL);
78
+	}
79
+
80
+	/**
81
+	 * Decode the given data from the csv format
82
+	 *
83
+	 * @param string $data
84
+	 *            data sent from client to
85
+	 *            the api in the given format.
86
+	 *
87
+	 * @return array associative array of the parsed data
88
+	 */
89
+	public function decode($data)
90
+	{
91
+		$decoded = array();
92
+
93
+		if (empty($data)) {
94
+			return $decoded;
95
+		}
96
+
97
+		$lines = array_filter(explode(PHP_EOL, $data));
98
+
99
+		$keys = false;
100
+		$row = static::getRow(array_shift($lines));
101
+
102
+		if (is_null(static::$haveHeaders)) {
103
+			//try to guess with the given data
104
+			static::$haveHeaders = !count(array_filter($row, 'is_numeric'));
105
+		}
106
+
107
+		static::$haveHeaders ? $keys = $row : $decoded[] = $row;
108
+
109
+		while (($row = static::getRow(array_shift($lines), $keys)) !== FALSE)
110
+			$decoded [] = $row;
111
+
112
+		$char = Obj::$separatorChar;
113
+		Obj::$separatorChar = false;
114
+		$decoded = Obj::toArray($decoded);
115
+		Obj::$separatorChar = $char;
116
+		return $decoded;
117
+	}
118
+
119
+	protected static function getRow($data, $keys = false)
120
+	{
121
+		if (empty($data)) {
122
+			return false;
123
+		}
124
+		$line = str_getcsv(
125
+			$data,
126
+			static::$delimiter,
127
+			static::$enclosure,
128
+			static::$escape
129
+		);
130
+
131
+		$row = array();
132
+		foreach ($line as $key => $value) {
133
+			if (is_numeric($value))
134
+				$value = floatval($value);
135
+			if ($keys) {
136
+				if (isset($keys [$key]))
137
+					$row [$keys [$key]] = $value;
138
+			} else {
139
+				$row [$key] = $value;
140
+			}
141
+		}
142
+		if ($keys) {
143
+			for ($i = count($row); $i < count($keys); $i++) {
144
+				$row[$keys[$i]] = null;
145
+			}
146
+		}
147
+		return $row;
148
+	}
149
+
150
+	/**
151
+	 * Decode the given data stream
152
+	 *
153
+	 * @param string $stream A stream resource with data
154
+	 *                       sent from client to the api
155
+	 *                       in the given format.
156
+	 *
157
+	 * @return array associative array of the parsed data
158
+	 */
159
+	public function decodeStream($stream)
160
+	{
161
+		$decoded = array();
162
+
163
+		$keys = false;
164
+		$row = static::getRow(stream_get_line($stream, 0, PHP_EOL));
165
+		if (is_null(static::$haveHeaders)) {
166
+			//try to guess with the given data
167
+			static::$haveHeaders = !count(array_filter($row, 'is_numeric'));
168
+		}
169
+
170
+		static::$haveHeaders ? $keys = $row : $decoded[] = $row;
171
+
172
+		while (($row = static::getRow(stream_get_line($stream, 0, PHP_EOL), $keys)) !== FALSE)
173
+			$decoded [] = $row;
174
+
175
+		$char = Obj::$separatorChar;
176
+		Obj::$separatorChar = false;
177
+		$decoded = Obj::toArray($decoded);
178
+		Obj::$separatorChar = $char;
179
+		return $decoded;
180
+	}
181 181
 }
182 182
\ No newline at end of file
Please login to merge, or discard this patch.
htdocs/includes/restler/framework/Luracast/Restler/Format/TsvFormat.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -15,10 +15,10 @@
 block discarded – undo
15 15
  */
16 16
 class TsvFormat extends CsvFormat
17 17
 {
18
-    const MIME = 'text/csv';
19
-    const EXTENSION = 'csv';
20
-    public static $delimiter = "\t";
21
-    public static $enclosure = '"';
22
-    public static $escape = '\\';
23
-    public static $haveHeaders = null;
18
+	const MIME = 'text/csv';
19
+	const EXTENSION = 'csv';
20
+	public static $delimiter = "\t";
21
+	public static $enclosure = '"';
22
+	public static $escape = '\\';
23
+	public static $haveHeaders = null;
24 24
 }
25 25
\ No newline at end of file
Please login to merge, or discard this patch.
htdocs/includes/restler/framework/Luracast/Restler/Format/XmlFormat.php 1 patch
Indentation   +313 added lines, -313 removed lines patch added patch discarded remove patch
@@ -20,334 +20,334 @@
 block discarded – undo
20 20
  */
21 21
 class XmlFormat extends Format
22 22
 {
23
-    const MIME = 'application/xml';
24
-    const EXTENSION = 'xml';
23
+	const MIME = 'application/xml';
24
+	const EXTENSION = 'xml';
25 25
 
26
-    // ==================================================================
27
-    //
28
-    // Properties related to reading/parsing/decoding xml
29
-    //
30
-    // ------------------------------------------------------------------
31
-    public static $importSettingsFromXml = false;
32
-    public static $parseAttributes = true;
33
-    public static $parseNamespaces = true;
34
-    public static $parseTextNodeAsProperty = true;
26
+	// ==================================================================
27
+	//
28
+	// Properties related to reading/parsing/decoding xml
29
+	//
30
+	// ------------------------------------------------------------------
31
+	public static $importSettingsFromXml = false;
32
+	public static $parseAttributes = true;
33
+	public static $parseNamespaces = true;
34
+	public static $parseTextNodeAsProperty = true;
35 35
 
36
-    // ==================================================================
37
-    //
38
-    // Properties related to writing/encoding xml
39
-    //
40
-    // ------------------------------------------------------------------
41
-    public static $useTextNodeProperty = true;
42
-    public static $useNamespaces = true;
43
-    public static $cdataNames = array();
36
+	// ==================================================================
37
+	//
38
+	// Properties related to writing/encoding xml
39
+	//
40
+	// ------------------------------------------------------------------
41
+	public static $useTextNodeProperty = true;
42
+	public static $useNamespaces = true;
43
+	public static $cdataNames = array();
44 44
 
45
-    // ==================================================================
46
-    //
47
-    // Common Properties
48
-    //
49
-    // ------------------------------------------------------------------
50
-    public static $attributeNames = array();
51
-    public static $textNodeName = 'text';
52
-    public static $namespaces = array();
53
-    public static $namespacedProperties = array();
54
-    /**
55
-     * Default name for the root node.
56
-     *
57
-     * @var string $rootNodeName
58
-     */
59
-    public static $rootName = 'response';
60
-    public static $defaultTagName = 'item';
45
+	// ==================================================================
46
+	//
47
+	// Common Properties
48
+	//
49
+	// ------------------------------------------------------------------
50
+	public static $attributeNames = array();
51
+	public static $textNodeName = 'text';
52
+	public static $namespaces = array();
53
+	public static $namespacedProperties = array();
54
+	/**
55
+	 * Default name for the root node.
56
+	 *
57
+	 * @var string $rootNodeName
58
+	 */
59
+	public static $rootName = 'response';
60
+	public static $defaultTagName = 'item';
61 61
 
62
-    /**
63
-     * When you decode an XML its structure is copied to the static vars
64
-     * we can use this function to echo them out and then copy paste inside
65
-     * our service methods
66
-     *
67
-     * @return string PHP source code to reproduce the configuration
68
-     */
69
-    public static function exportCurrentSettings()
70
-    {
71
-        $s = 'XmlFormat::$rootName = "' . (self::$rootName) . "\";\n";
72
-        $s .= 'XmlFormat::$attributeNames = ' .
73
-            (var_export(self::$attributeNames, true)) . ";\n";
74
-        $s .= 'XmlFormat::$defaultTagName = "' .
75
-            self::$defaultTagName . "\";\n";
76
-        $s .= 'XmlFormat::$parseAttributes = ' .
77
-            (self::$parseAttributes ? 'true' : 'false') . ";\n";
78
-        $s .= 'XmlFormat::$parseNamespaces = ' .
79
-            (self::$parseNamespaces ? 'true' : 'false') . ";\n";
80
-        if (self::$parseNamespaces) {
81
-            $s .= 'XmlFormat::$namespaces = ' .
82
-                (var_export(self::$namespaces, true)) . ";\n";
83
-            $s .= 'XmlFormat::$namespacedProperties = ' .
84
-                (var_export(self::$namespacedProperties, true)) . ";\n";
85
-        }
62
+	/**
63
+	 * When you decode an XML its structure is copied to the static vars
64
+	 * we can use this function to echo them out and then copy paste inside
65
+	 * our service methods
66
+	 *
67
+	 * @return string PHP source code to reproduce the configuration
68
+	 */
69
+	public static function exportCurrentSettings()
70
+	{
71
+		$s = 'XmlFormat::$rootName = "' . (self::$rootName) . "\";\n";
72
+		$s .= 'XmlFormat::$attributeNames = ' .
73
+			(var_export(self::$attributeNames, true)) . ";\n";
74
+		$s .= 'XmlFormat::$defaultTagName = "' .
75
+			self::$defaultTagName . "\";\n";
76
+		$s .= 'XmlFormat::$parseAttributes = ' .
77
+			(self::$parseAttributes ? 'true' : 'false') . ";\n";
78
+		$s .= 'XmlFormat::$parseNamespaces = ' .
79
+			(self::$parseNamespaces ? 'true' : 'false') . ";\n";
80
+		if (self::$parseNamespaces) {
81
+			$s .= 'XmlFormat::$namespaces = ' .
82
+				(var_export(self::$namespaces, true)) . ";\n";
83
+			$s .= 'XmlFormat::$namespacedProperties = ' .
84
+				(var_export(self::$namespacedProperties, true)) . ";\n";
85
+		}
86 86
 
87
-        return $s;
88
-    }
87
+		return $s;
88
+	}
89 89
 
90
-    public function encode($data, $humanReadable = false)
91
-    {
92
-        $data = Obj::toArray($data);
93
-        $xml = new XMLWriter();
94
-        $xml->openMemory();
95
-        $xml->startDocument('1.0', $this->charset);
96
-        if ($humanReadable) {
97
-            $xml->setIndent(true);
98
-            $xml->setIndentString('    ');
99
-        }
100
-        static::$useNamespaces && isset(static::$namespacedProperties[static::$rootName])
101
-            ?
102
-            $xml->startElementNs(
103
-                static::$namespacedProperties[static::$rootName],
104
-                static::$rootName,
105
-                static::$namespaces[static::$namespacedProperties[static::$rootName]]
106
-            )
107
-            :
108
-            $xml->startElement(static::$rootName);
109
-        if (static::$useNamespaces) {
110
-            foreach (static::$namespaces as $prefix => $ns) {
111
-                if (isset(static::$namespacedProperties[static::$rootName])
112
-                    && static::$namespacedProperties[static::$rootName] == $prefix
113
-                ) {
114
-                    continue;
115
-                }
116
-                $prefix = 'xmlns' . (empty($prefix) ? '' : ':' . $prefix);
117
-                $xml->writeAttribute($prefix, $ns);
118
-            }
119
-        }
120
-        $this->write($xml, $data, static::$rootName);
121
-        $xml->endElement();
90
+	public function encode($data, $humanReadable = false)
91
+	{
92
+		$data = Obj::toArray($data);
93
+		$xml = new XMLWriter();
94
+		$xml->openMemory();
95
+		$xml->startDocument('1.0', $this->charset);
96
+		if ($humanReadable) {
97
+			$xml->setIndent(true);
98
+			$xml->setIndentString('    ');
99
+		}
100
+		static::$useNamespaces && isset(static::$namespacedProperties[static::$rootName])
101
+			?
102
+			$xml->startElementNs(
103
+				static::$namespacedProperties[static::$rootName],
104
+				static::$rootName,
105
+				static::$namespaces[static::$namespacedProperties[static::$rootName]]
106
+			)
107
+			:
108
+			$xml->startElement(static::$rootName);
109
+		if (static::$useNamespaces) {
110
+			foreach (static::$namespaces as $prefix => $ns) {
111
+				if (isset(static::$namespacedProperties[static::$rootName])
112
+					&& static::$namespacedProperties[static::$rootName] == $prefix
113
+				) {
114
+					continue;
115
+				}
116
+				$prefix = 'xmlns' . (empty($prefix) ? '' : ':' . $prefix);
117
+				$xml->writeAttribute($prefix, $ns);
118
+			}
119
+		}
120
+		$this->write($xml, $data, static::$rootName);
121
+		$xml->endElement();
122 122
 
123
-        return $xml->outputMemory();
124
-    }
123
+		return $xml->outputMemory();
124
+	}
125 125
 
126
-    public function write(XMLWriter $xml, $data, $parent)
127
-    {
128
-        $text = array();
129
-        if (is_array($data)) {
130
-            if (static::$useTextNodeProperty && isset($data[static::$textNodeName])) {
131
-                $text [] = $data[static::$textNodeName];
132
-                unset($data[static::$textNodeName]);
133
-            }
134
-            $attributes = array_flip(static::$attributeNames);
135
-            //make sure we deal with attributes first
136
-            $temp = array();
137
-            foreach ($data as $key => $value) {
138
-                if (isset($attributes[$key])) {
139
-                    $temp[$key] = $data[$key];
140
-                    unset($data[$key]);
141
-                }
142
-            }
143
-            $data = array_merge($temp, $data);
144
-            foreach ($data as $key => $value) {
145
-                if (is_numeric($key)) {
146
-                    if (!is_array($value)) {
147
-                        $text [] = $value;
148
-                        continue;
149
-                    }
150
-                    $key = static::$defaultTagName;
151
-                }
152
-                $useNS = static::$useNamespaces
153
-                    && !empty(static::$namespacedProperties[$key])
154
-                    && false === strpos($key, ':');
155
-                if (is_array($value)) {
156
-                    $useNS
157
-                        ? $xml->startElementNs(
158
-                        static::$namespacedProperties[$key],
159
-                        $key,
160
-                        null
161
-                    )
162
-                        : $xml->startElement($key);
163
-                    $this->write($xml, $value, $key);
164
-                    $xml->endElement();
165
-                    continue;
166
-                } elseif (is_bool($value)) {
167
-                    $value = $value ? 'true' : 'false';
168
-                }
169
-                if (isset($attributes[$key])) {
170
-                    $xml->writeAttribute($useNS ? static::$namespacedProperties[$key] . ':' . $key : $key, $value);
171
-                } else {
172
-                    $useNS
173
-                        ?
174
-                        $xml->startElementNs(
175
-                            static::$namespacedProperties[$key],
176
-                            $key,
177
-                            null
178
-                        )
179
-                        : $xml->startElement($key);
180
-                    $this->write($xml, $value, $key);
181
-                    $xml->endElement();
182
-                }
183
-            }
184
-        } else {
185
-            $text [] = (string)$data;
186
-        }
187
-        if (!empty($text)) {
188
-            if (count($text) == 1) {
189
-                in_array($parent, static::$cdataNames)
190
-                    ? $xml->writeCdata(implode('', $text))
191
-                    : $xml->text(implode('', $text));
192
-            } else {
193
-                foreach ($text as $t) {
194
-                    $xml->writeElement(static::$textNodeName, $t);
195
-                }
196
-            }
197
-        }
198
-    }
126
+	public function write(XMLWriter $xml, $data, $parent)
127
+	{
128
+		$text = array();
129
+		if (is_array($data)) {
130
+			if (static::$useTextNodeProperty && isset($data[static::$textNodeName])) {
131
+				$text [] = $data[static::$textNodeName];
132
+				unset($data[static::$textNodeName]);
133
+			}
134
+			$attributes = array_flip(static::$attributeNames);
135
+			//make sure we deal with attributes first
136
+			$temp = array();
137
+			foreach ($data as $key => $value) {
138
+				if (isset($attributes[$key])) {
139
+					$temp[$key] = $data[$key];
140
+					unset($data[$key]);
141
+				}
142
+			}
143
+			$data = array_merge($temp, $data);
144
+			foreach ($data as $key => $value) {
145
+				if (is_numeric($key)) {
146
+					if (!is_array($value)) {
147
+						$text [] = $value;
148
+						continue;
149
+					}
150
+					$key = static::$defaultTagName;
151
+				}
152
+				$useNS = static::$useNamespaces
153
+					&& !empty(static::$namespacedProperties[$key])
154
+					&& false === strpos($key, ':');
155
+				if (is_array($value)) {
156
+					$useNS
157
+						? $xml->startElementNs(
158
+						static::$namespacedProperties[$key],
159
+						$key,
160
+						null
161
+					)
162
+						: $xml->startElement($key);
163
+					$this->write($xml, $value, $key);
164
+					$xml->endElement();
165
+					continue;
166
+				} elseif (is_bool($value)) {
167
+					$value = $value ? 'true' : 'false';
168
+				}
169
+				if (isset($attributes[$key])) {
170
+					$xml->writeAttribute($useNS ? static::$namespacedProperties[$key] . ':' . $key : $key, $value);
171
+				} else {
172
+					$useNS
173
+						?
174
+						$xml->startElementNs(
175
+							static::$namespacedProperties[$key],
176
+							$key,
177
+							null
178
+						)
179
+						: $xml->startElement($key);
180
+					$this->write($xml, $value, $key);
181
+					$xml->endElement();
182
+				}
183
+			}
184
+		} else {
185
+			$text [] = (string)$data;
186
+		}
187
+		if (!empty($text)) {
188
+			if (count($text) == 1) {
189
+				in_array($parent, static::$cdataNames)
190
+					? $xml->writeCdata(implode('', $text))
191
+					: $xml->text(implode('', $text));
192
+			} else {
193
+				foreach ($text as $t) {
194
+					$xml->writeElement(static::$textNodeName, $t);
195
+				}
196
+			}
197
+		}
198
+	}
199 199
 
200
-    public function decode($data)
201
-    {
202
-        try {
203
-            if ($data == '') {
204
-                return array();
205
-            }
206
-            libxml_use_internal_errors(true);
207
-            libxml_disable_entity_loader(true);
208
-            $xml = simplexml_load_string($data,
209
-                "SimpleXMLElement", LIBXML_NOBLANKS | LIBXML_NOCDATA | LIBXML_COMPACT);
210
-            if (false === $xml) {
211
-                $error = libxml_get_last_error();
212
-                throw new RestException(400, 'Malformed XML. '
213
-                    . trim($error->message, "\r\n") . ' at line ' . $error->line);
214
-            }
215
-            libxml_clear_errors();
216
-            if (static::$importSettingsFromXml) {
217
-                static::$attributeNames = array();
218
-                static::$namespacedProperties = array();
219
-                static::$namespaces = array();
220
-                static::$rootName = $xml->getName();
221
-                $namespaces = $xml->getNamespaces();
222
-                if (count($namespaces)) {
223
-                    $p = strpos($data, $xml->getName());
224
-                    if ($p && $data[$p - 1] == ':') {
225
-                        $s = strpos($data, '<') + 1;
226
-                        $prefix = substr($data, $s, $p - $s - 1);
227
-                        static::$namespacedProperties[static::$rootName] = $prefix;
228
-                    }
229
-                }
230
-            }
231
-            $data = $this->read($xml);
232
-            if (count($data) == 1 && isset($data[static::$textNodeName])) {
233
-                $data = $data[static::$textNodeName];
234
-            }
200
+	public function decode($data)
201
+	{
202
+		try {
203
+			if ($data == '') {
204
+				return array();
205
+			}
206
+			libxml_use_internal_errors(true);
207
+			libxml_disable_entity_loader(true);
208
+			$xml = simplexml_load_string($data,
209
+				"SimpleXMLElement", LIBXML_NOBLANKS | LIBXML_NOCDATA | LIBXML_COMPACT);
210
+			if (false === $xml) {
211
+				$error = libxml_get_last_error();
212
+				throw new RestException(400, 'Malformed XML. '
213
+					. trim($error->message, "\r\n") . ' at line ' . $error->line);
214
+			}
215
+			libxml_clear_errors();
216
+			if (static::$importSettingsFromXml) {
217
+				static::$attributeNames = array();
218
+				static::$namespacedProperties = array();
219
+				static::$namespaces = array();
220
+				static::$rootName = $xml->getName();
221
+				$namespaces = $xml->getNamespaces();
222
+				if (count($namespaces)) {
223
+					$p = strpos($data, $xml->getName());
224
+					if ($p && $data[$p - 1] == ':') {
225
+						$s = strpos($data, '<') + 1;
226
+						$prefix = substr($data, $s, $p - $s - 1);
227
+						static::$namespacedProperties[static::$rootName] = $prefix;
228
+					}
229
+				}
230
+			}
231
+			$data = $this->read($xml);
232
+			if (count($data) == 1 && isset($data[static::$textNodeName])) {
233
+				$data = $data[static::$textNodeName];
234
+			}
235 235
 
236
-            return $data;
237
-        } catch (\RuntimeException $e) {
238
-            throw new RestException(400,
239
-                "Error decoding request. " . $e->getMessage());
240
-        }
241
-    }
236
+			return $data;
237
+		} catch (\RuntimeException $e) {
238
+			throw new RestException(400,
239
+				"Error decoding request. " . $e->getMessage());
240
+		}
241
+	}
242 242
 
243
-    public function read(SimpleXMLElement $xml, $namespaces = null)
244
-    {
245
-        $r = array();
246
-        $text = (string)$xml;
243
+	public function read(SimpleXMLElement $xml, $namespaces = null)
244
+	{
245
+		$r = array();
246
+		$text = (string)$xml;
247 247
 
248
-        if (static::$parseAttributes) {
249
-            $attributes = $xml->attributes();
250
-            foreach ($attributes as $key => $value) {
251
-                if (static::$importSettingsFromXml
252
-                    && !in_array($key, static::$attributeNames)
253
-                ) {
254
-                    static::$attributeNames[] = $key;
255
-                }
256
-                $r[$key] = static::setType((string)$value);
257
-            }
258
-        }
259
-        $children = $xml->children();
260
-        foreach ($children as $key => $value) {
261
-            if ($key == static::$defaultTagName) {
262
-                $r[] = $this->read($value);
263
-            } elseif (isset($r[$key])) {
264
-                if (is_array($r[$key])) {
265
-                    if ($r[$key] != array_values($r[$key])) {
266
-                        $r[$key] = array($r[$key]);
267
-                    }
268
-                } else {
269
-                    $r[$key] = array($r[$key]);
270
-                }
271
-                $r[$key][] = $this->read($value, $namespaces);
272
-            } else {
273
-                $r[$key] = $this->read($value);
274
-            }
275
-        }
248
+		if (static::$parseAttributes) {
249
+			$attributes = $xml->attributes();
250
+			foreach ($attributes as $key => $value) {
251
+				if (static::$importSettingsFromXml
252
+					&& !in_array($key, static::$attributeNames)
253
+				) {
254
+					static::$attributeNames[] = $key;
255
+				}
256
+				$r[$key] = static::setType((string)$value);
257
+			}
258
+		}
259
+		$children = $xml->children();
260
+		foreach ($children as $key => $value) {
261
+			if ($key == static::$defaultTagName) {
262
+				$r[] = $this->read($value);
263
+			} elseif (isset($r[$key])) {
264
+				if (is_array($r[$key])) {
265
+					if ($r[$key] != array_values($r[$key])) {
266
+						$r[$key] = array($r[$key]);
267
+					}
268
+				} else {
269
+					$r[$key] = array($r[$key]);
270
+				}
271
+				$r[$key][] = $this->read($value, $namespaces);
272
+			} else {
273
+				$r[$key] = $this->read($value);
274
+			}
275
+		}
276 276
 
277
-        if (static::$parseNamespaces) {
278
-            if (is_null($namespaces)) {
279
-                $namespaces = $xml->getDocNamespaces(true);
280
-            }
281
-            foreach ($namespaces as $prefix => $ns) {
282
-                static::$namespaces[$prefix] = $ns;
283
-                if (static::$parseAttributes) {
284
-                    $attributes = $xml->attributes($ns);
285
-                    foreach ($attributes as $key => $value) {
286
-                        if (isset($r[$key])) {
287
-                            $key = "{$prefix}:$key";
288
-                        }
289
-                        if (static::$importSettingsFromXml
290
-                            && !in_array($key, static::$attributeNames)
291
-                        ) {
292
-                            static::$namespacedProperties[$key] = $prefix;
293
-                            static::$attributeNames[] = $key;
294
-                        }
295
-                        $r[$key] = static::setType((string)$value);
296
-                    }
297
-                }
298
-                $children = $xml->children($ns);
299
-                foreach ($children as $key => $value) {
300
-                    if (static::$importSettingsFromXml) {
301
-                        static::$namespacedProperties[$key] = $prefix;
302
-                    }
303
-                    if (isset($r[$key])) {
304
-                        if (is_array($r[$key])) {
305
-                            if ($r[$key] != array_values($r[$key])) {
306
-                                $r[$key] = array($r[$key]);
307
-                            }
308
-                        } else {
309
-                            $r[$key] = array($r[$key]);
310
-                        }
311
-                        $r[$key][] = $this->read($value, $namespaces);
312
-                    } else {
313
-                        $r[$key] = $this->read($value, $namespaces);
314
-                    }
315
-                }
316
-            }
317
-        }
277
+		if (static::$parseNamespaces) {
278
+			if (is_null($namespaces)) {
279
+				$namespaces = $xml->getDocNamespaces(true);
280
+			}
281
+			foreach ($namespaces as $prefix => $ns) {
282
+				static::$namespaces[$prefix] = $ns;
283
+				if (static::$parseAttributes) {
284
+					$attributes = $xml->attributes($ns);
285
+					foreach ($attributes as $key => $value) {
286
+						if (isset($r[$key])) {
287
+							$key = "{$prefix}:$key";
288
+						}
289
+						if (static::$importSettingsFromXml
290
+							&& !in_array($key, static::$attributeNames)
291
+						) {
292
+							static::$namespacedProperties[$key] = $prefix;
293
+							static::$attributeNames[] = $key;
294
+						}
295
+						$r[$key] = static::setType((string)$value);
296
+					}
297
+				}
298
+				$children = $xml->children($ns);
299
+				foreach ($children as $key => $value) {
300
+					if (static::$importSettingsFromXml) {
301
+						static::$namespacedProperties[$key] = $prefix;
302
+					}
303
+					if (isset($r[$key])) {
304
+						if (is_array($r[$key])) {
305
+							if ($r[$key] != array_values($r[$key])) {
306
+								$r[$key] = array($r[$key]);
307
+							}
308
+						} else {
309
+							$r[$key] = array($r[$key]);
310
+						}
311
+						$r[$key][] = $this->read($value, $namespaces);
312
+					} else {
313
+						$r[$key] = $this->read($value, $namespaces);
314
+					}
315
+				}
316
+			}
317
+		}
318 318
 
319
-        if (empty($text) && $text !== '0') {
320
-            if (empty($r)) {
321
-                return null;
322
-            }
323
-        } else {
324
-            empty($r)
325
-                ? $r = static::setType($text)
326
-                : (
327
-            static::$parseTextNodeAsProperty
328
-                ? $r[static::$textNodeName] = static::setType($text)
329
-                : $r[] = static::setType($text)
330
-            );
331
-        }
319
+		if (empty($text) && $text !== '0') {
320
+			if (empty($r)) {
321
+				return null;
322
+			}
323
+		} else {
324
+			empty($r)
325
+				? $r = static::setType($text)
326
+				: (
327
+			static::$parseTextNodeAsProperty
328
+				? $r[static::$textNodeName] = static::setType($text)
329
+				: $r[] = static::setType($text)
330
+			);
331
+		}
332 332
 
333
-        return $r;
334
-    }
333
+		return $r;
334
+	}
335 335
 
336
-    public static function setType($value)
337
-    {
338
-        if (empty($value) && $value !== '0') {
339
-            return null;
340
-        }
341
-        if ($value == 'true') {
342
-            return true;
343
-        }
344
-        if ($value == 'false') {
345
-            return true;
346
-        }
347
-        if (is_numeric($value)) {
348
-            return 0 + $value;
349
-        }
336
+	public static function setType($value)
337
+	{
338
+		if (empty($value) && $value !== '0') {
339
+			return null;
340
+		}
341
+		if ($value == 'true') {
342
+			return true;
343
+		}
344
+		if ($value == 'false') {
345
+			return true;
346
+		}
347
+		if (is_numeric($value)) {
348
+			return 0 + $value;
349
+		}
350 350
 
351
-        return $value;
352
-    }
351
+		return $value;
352
+	}
353 353
 }
Please login to merge, or discard this patch.
htdocs/includes/restler/framework/Luracast/Restler/Format/HtmlFormat.php 1 patch
Indentation   +521 added lines, -521 removed lines patch added patch discarded remove patch
@@ -38,525 +38,525 @@
 block discarded – undo
38 38
  */
39 39
 class HtmlFormat extends DependentFormat
40 40
 {
41
-    const BLADE = 'Illuminate\View\View';
42
-    const TWIG = 'Twig\Environment';
43
-    const MUSTACHE = 'Mustache_Engine';
44
-
45
-    public static $mime = 'text/html';
46
-    public static $extension = 'html';
47
-    public static $view;
48
-    public static $errorView = 'debug.php';
49
-    public static $template = 'php';
50
-    public static $handleSession = true;
51
-    public static $convertResponseToArray = false;
52
-
53
-    public static $useSmartViews = true;
54
-    /**
55
-     * @var null|string defaults to template named folder in Defaults::$cacheDirectory
56
-     */
57
-    public static $cacheDirectory = null;
58
-    /**
59
-     * @var array global key value pair to be supplied to the templates. All
60
-     * keys added here will be available as a variable inside the template
61
-     */
62
-    public static $data = array();
63
-    /**
64
-     * @var string set it to the location of your the view files. Defaults to
65
-     * views folder which is same level as vendor directory.
66
-     */
67
-    public static $viewPath;
68
-    /**
69
-     * @var array template and its custom extension key value pair
70
-     */
71
-    public static $customTemplateExtensions = array('blade' => 'blade.php');
72
-    /**
73
-     * @var bool used internally for error handling
74
-     */
75
-    protected static $parseViewMetadata = true;
76
-    /**
77
-     * @var Restler;
78
-     */
79
-    public $restler;
80
-
81
-    public function __construct()
82
-    {
83
-        //============ SESSION MANAGEMENT =============//
84
-        if (static::$handleSession) {
85
-            if (session_start() && isset($_SESSION['flash'])) {
86
-                static::$data['flash'] = $_SESSION['flash'];
87
-                unset($_SESSION['flash']);
88
-            }
89
-        }
90
-        if (!static::$viewPath) {
91
-            $array = explode('vendor', __DIR__, 2);
92
-            static::$viewPath = $array[0] . 'views';
93
-        }
94
-    }
95
-
96
-    public function getDependencyMap()
97
-    {
98
-        return array(
99
-            self::BLADE    => 'illuminate/view:^8',
100
-            self::TWIG     => 'twig/twig:^3',
101
-            self::MUSTACHE => 'mustache/mustache:dev-master',
102
-        );
103
-    }
104
-
105
-    public static function blade(array $data, $debug = true)
106
-    {
107
-        $resolver = new EngineResolver();
108
-        $files = new Filesystem();
109
-        $compiler = new BladeCompiler($files, static::$cacheDirectory);
110
-        $engine = new CompilerEngine($compiler);
111
-        $resolver->register('blade', function () use ($engine) {
112
-            return $engine;
113
-        });
114
-        $phpEngine = new PhpEngine($files);
115
-        $resolver->register('php', function () use ($phpEngine) {
116
-            return $phpEngine;
117
-        });
118
-
119
-        /** @var Restler $restler */
120
-        $restler = Scope::get('Restler');
121
-
122
-        //Lets expose shortcuts for our classes
123
-        spl_autoload_register(function ($className) use ($restler) {
124
-            if (isset($restler->apiMethodInfo->metadata['scope'][$className])) {
125
-                return class_alias($restler->apiMethodInfo->metadata['scope'][$className], $className);
126
-            }
127
-            if (isset(Scope::$classAliases[$className])) {
128
-                return class_alias(Scope::$classAliases[$className], $className);
129
-            }
130
-            return false;
131
-        }, true, true);
132
-
133
-        $viewFinder = new FileViewFinder($files, array(static::$viewPath));
134
-        $factory = new Factory($resolver, $viewFinder, new Dispatcher());
135
-        $path = $viewFinder->find(self::$view);
136
-        $view = new View($factory, $engine, self::$view, $path, $data);
137
-        $factory->callCreator($view);
138
-        return $view->render();
139
-    }
140
-
141
-    /**
142
-     * @param array|object $data
143
-     * @param bool         $debug
144
-     *
145
-     * @return string
146
-     * @throws \Twig\Error\LoaderError
147
-     * @throws \Twig\Error\RuntimeError
148
-     * @throws \Twig\Error\SyntaxError
149
-     */
150
-    public static function twig($data, $debug = true)
151
-    {
152
-        $loader = new FilesystemLoader(static::$viewPath);
153
-        $twig = new Environment($loader, array(
154
-            'cache'                => is_string(static::$cacheDirectory)
155
-                ? static::$cacheDirectory : false,
156
-            'debug'                => $debug,
157
-            'use_strict_variables' => $debug,
158
-        ));
159
-        if ($debug) {
160
-            $twig->addExtension(new DebugExtension());
161
-        }
162
-
163
-        $twig->addFunction(
164
-            new TwigFunction(
165
-                'form',
166
-                'Luracast\Restler\UI\Forms::get',
167
-                array('is_safe' => array('html'))
168
-            )
169
-        );
170
-        $twig->addFunction(
171
-            new TwigFunction(
172
-                'form_key',
173
-                'Luracast\Restler\UI\Forms::key'
174
-            )
175
-        );
176
-        $twig->addFunction(
177
-            new TwigFunction(
178
-                'nav',
179
-                'Luracast\Restler\UI\Nav::get'
180
-            )
181
-        );
182
-
183
-        $twig->registerUndefinedFunctionCallback(function ($name) {
184
-            if (
185
-                isset(HtmlFormat::$data[$name]) &&
186
-                is_callable(HtmlFormat::$data[$name])
187
-            ) {
188
-                return new TwigFunction(
189
-                    $name,
190
-                    HtmlFormat::$data[$name]
191
-                );
192
-            }
193
-            return false;
194
-        });
195
-
196
-        $template = $twig->load(static::getViewFile());
197
-        return $template->render((array)$data);
198
-    }
199
-
200
-    /**
201
-     * @param array|object $data
202
-     * @param bool         $debug
203
-     *
204
-     * @return string
205
-     */
206
-    public static function handlebar($data, $debug = true)
207
-    {
208
-        return static::mustache($data, $debug);
209
-    }
210
-
211
-    /**
212
-     * @param array|object $data
213
-     * @param bool         $debug
214
-     *
215
-     * @return string
216
-     */
217
-    public static function mustache($data, $debug = true)
218
-    {
219
-        $data = (array)$data;
220
-        if (!isset($data['nav'])) {
221
-            $data['nav'] = array_values(Nav::get());
222
-        }
223
-        $options = array(
224
-            'loader'  => new \Mustache_Loader_FilesystemLoader(
225
-                static::$viewPath,
226
-                array('extension' => static::getViewExtension())
227
-            ),
228
-            'helpers' => array(
229
-                'form' => function ($text, \Mustache_LambdaHelper $m) {
230
-                    $params = explode(',', $m->render($text));
231
-                    return call_user_func_array(
232
-                        'Luracast\Restler\UI\Forms::get',
233
-                        $params
234
-                    );
235
-                },
236
-            )
237
-        );
238
-        if (!$debug) {
239
-            $options['cache'] = static::$cacheDirectory;
240
-        }
241
-        $m = new \Mustache_Engine($options);
242
-        return $m->render(static::getViewFile(), $data);
243
-    }
244
-
245
-    /**
246
-     * @param array|object $data
247
-     * @param bool         $debug
248
-     *
249
-     * @return string
250
-     * @throws RestException
251
-     */
252
-    public static function php($data, $debug = true)
253
-    {
254
-        if (static::$view == 'debug') {
255
-            static::$viewPath = dirname(__DIR__) . '/views';
256
-        }
257
-        $view = static::getViewFile(true);
258
-
259
-        if (!is_readable($view)) {
260
-            throw new RestException(
261
-                500,
262
-                "view file `$view` is not readable. " .
263
-                'Check for file presence and file permissions'
264
-            );
265
-        }
266
-
267
-        $path = static::$viewPath . DIRECTORY_SEPARATOR;
268
-        $template = function ($view) use ($data, $path) {
269
-            $data = (array)$data;
270
-            $form = function () {
271
-                return call_user_func_array(
272
-                    'Luracast\Restler\UI\Forms::get',
273
-                    func_get_args()
274
-                );
275
-            };
276
-            if (!isset($data['form'])) {
277
-                $data['form'] = $form;
278
-            }
279
-            $nav = function () {
280
-                return call_user_func_array(
281
-                    'Luracast\Restler\UI\Nav::get',
282
-                    func_get_args()
283
-                );
284
-            };
285
-            if (!isset($data['nav'])) {
286
-                $data['nav'] = $nav;
287
-            }
288
-
289
-
290
-            $_ = function () use ($data, $path) {
291
-                extract($data);
292
-                $args = func_get_args();
293
-                $task = array_shift($args);
294
-                switch ($task) {
295
-                    case 'require':
296
-                    case 'include':
297
-                        $file = $path . $args[0];
298
-                        if (is_readable($file)) {
299
-                            if (
300
-                                isset($args[1]) &&
301
-                                ($arrays = Util::nestedValue($data, $args[1]))
302
-                            ) {
303
-                                $str = '';
304
-                                foreach ($arrays as $arr) {
305
-                                    extract((array)$arr);
306
-                                    $str .= include $file;
307
-                                }
308
-                                return $str;
309
-                            } else {
310
-                                return include $file;
311
-                            }
312
-                        }
313
-                        break;
314
-                    case 'if':
315
-                        if (count($args) < 2) {
316
-                            $args[1] = '';
317
-                        }
318
-                        if (count($args) < 3) {
319
-                            $args[2] = '';
320
-                        }
321
-                        return $args[0] ? $args[1] : $args[2];
322
-                        break;
323
-                    default:
324
-                        if (isset($data[$task]) && is_callable($data[$task])) {
325
-                            return call_user_func_array($data[$task], $args);
326
-                        }
327
-                }
328
-                return '';
329
-            };
330
-            extract($data);
331
-            return @include $view;
332
-        };
333
-        $value = $template($view);
334
-        if (is_string($value)) {
335
-            return $value;
336
-        }
337
-    }
338
-
339
-    /**
340
-     * Encode the given data in the format
341
-     *
342
-     * @param array   $data                resulting data that needs to
343
-     *                                     be encoded in the given format
344
-     * @param boolean $humanReadable       set to TRUE when restler
345
-     *                                     is not running in production mode.
346
-     *                                     Formatter has to make the encoded
347
-     *                                     output more human readable
348
-     *
349
-     * @return string encoded string
350
-     * @throws \Exception
351
-     */
352
-    public function encode($data, $humanReadable = false)
353
-    {
354
-        if (!is_readable(static::$viewPath)) {
355
-            throw new \Exception(
356
-                'The views directory `'
357
-                . self::$viewPath . '` should exist with read permission.'
358
-            );
359
-        }
360
-        static::$data['basePath'] = dirname($_SERVER['SCRIPT_NAME']);
361
-        static::$data['baseUrl'] = $this->restler->getBaseUrl();
362
-        static::$data['currentPath'] = $this->restler->url;
363
-
364
-        try {
365
-            $exception = $this->restler->exception;
366
-            $success = is_null($exception);
367
-            $error = $success ? null : $exception->getMessage();
368
-            $data = array(
369
-                'response' => static::$convertResponseToArray
370
-                    ? Obj::toArray($data)
371
-                    : $data,
372
-                'stages'   => $this->restler->getEvents(),
373
-                'success'  => $success,
374
-                'error'    => $error
375
-            );
376
-            $info = $data['api'] = $this->restler->apiMethodInfo;
377
-            $metadata = Util::nestedValue(
378
-                $this->restler, 'apiMethodInfo', 'metadata'
379
-            );
380
-            $view = $success ? 'view' : 'errorView';
381
-            $value = false;
382
-            if (static::$parseViewMetadata && isset($metadata[$view])) {
383
-                if (is_array($metadata[$view])) {
384
-                    self::$view = $metadata[$view]['description'];
385
-                    $value = Util::nestedValue(
386
-                        $metadata[$view], 'properties', 'value'
387
-                    );
388
-                } else {
389
-                    self::$view = $metadata[$view];
390
-                }
391
-            } elseif (!self::$view) {
392
-                self::$view = static::guessViewName($this->restler->url);
393
-            }
394
-            if (
395
-                isset($metadata['param'])
396
-                && (!$value || 0 === strpos($value, 'request'))
397
-            ) {
398
-                $params = $metadata['param'];
399
-                foreach ($params as $index => &$param) {
400
-                    $index = intval($index);
401
-                    if (is_numeric($index)) {
402
-                        $param['value'] = $this
403
-                            ->restler
404
-                            ->apiMethodInfo
405
-                            ->parameters[$index];
406
-                    }
407
-                }
408
-                $data['request']['parameters'] = $params;
409
-            }
410
-            if ($value) {
411
-                $data = Util::nestedValue($data, explode('.', $value));
412
-            }
413
-            if (is_array($data)) {
414
-                $data += static::$data;
415
-            }
416
-            if (false === ($i = strrpos(self::$view, '.'))) {
417
-                $template = self::$template;
418
-            } else {
419
-                self::$template = $template = substr(self::$view, $i + 1);
420
-                self::$view = substr(self::$view, 0, $i);
421
-            }
422
-            if (!static::$cacheDirectory) {
423
-                static::$cacheDirectory = Defaults::$cacheDirectory . DIRECTORY_SEPARATOR . $template;
424
-                if (!file_exists(static::$cacheDirectory)) {
425
-                    if (!mkdir(static::$cacheDirectory, 0770, true)) {
426
-                        throw new RestException(500,
427
-                            'Unable to create cache directory `' . static::$cacheDirectory . '`');
428
-                    }
429
-                }
430
-            }
431
-            if (method_exists($class = get_called_class(), $template)) {
432
-                if ($template == 'blade') {
433
-                    $this->checkDependency(self::BLADE);
434
-                } elseif ($template == 'twig') {
435
-                    $this->checkDependency(self::TWIG);
436
-                } elseif ($template == 'mustache' || $template == 'handlebar') {
437
-                    $this->checkDependency(self::MUSTACHE);
438
-                }
439
-                return call_user_func("$class::$template", $data, $humanReadable);
440
-            }
441
-            throw new RestException(500, "Unsupported template system `$template`");
442
-        } catch (Exception $e) {
443
-            static::$parseViewMetadata = false;
444
-            $this->reset();
445
-            throw $e;
446
-        }
447
-    }
448
-
449
-    public static function guessViewName($path)
450
-    {
451
-        if (empty($path)) {
452
-            $path = 'index';
453
-        } elseif (strpos($path, '/')) {
454
-            $path .= '/index';
455
-        }
456
-        $file = static::$viewPath . '/' . $path . '.' . static::getViewExtension();
457
-
458
-        return static::$useSmartViews && is_readable($file)
459
-            ? $path
460
-            : static::$errorView;
461
-    }
462
-
463
-    public static function getViewExtension()
464
-    {
465
-        return isset(static::$customTemplateExtensions[static::$template])
466
-            ? static::$customTemplateExtensions[static::$template]
467
-            : static::$template;
468
-    }
469
-
470
-    public static function getViewFile($fullPath = false, $includeExtension = true)
471
-    {
472
-        $v = $fullPath ? static::$viewPath . '/' : '';
473
-        $v .= static::$view;
474
-        if ($includeExtension) {
475
-            $v .= '.' . static::getViewExtension();
476
-        }
477
-        return $v;
478
-    }
479
-
480
-    private function reset()
481
-    {
482
-        static::$mime = 'text/html';
483
-        static::$extension = 'html';
484
-        static::$view = 'debug';
485
-        static::$template = 'php';
486
-    }
487
-
488
-    /**
489
-     * Decode the given data from the format
490
-     *
491
-     * @param string $data
492
-     *            data sent from client to
493
-     *            the api in the given format.
494
-     *
495
-     * @return array associative array of the parsed data
496
-     *
497
-     * @throws RestException
498
-     */
499
-    public function decode($data)
500
-    {
501
-        throw new RestException(500, 'HtmlFormat is write only');
502
-    }
503
-
504
-    /**
505
-     * @return bool false as HTML format is write only
506
-     */
507
-    public function isReadable()
508
-    {
509
-        return false;
510
-    }
511
-
512
-    /**
513
-     * Get MIME type => Extension mappings as an associative array
514
-     *
515
-     * @return array list of mime strings for the format
516
-     * @example array('application/json'=>'json');
517
-     */
518
-    public function getMIMEMap()
519
-    {
520
-        return array(
521
-            static::$mime => static::$extension
522
-        );
523
-    }
524
-
525
-    /**
526
-     * Set the selected MIME type
527
-     *
528
-     * @param string $mime MIME type
529
-     */
530
-    public function setMIME($mime)
531
-    {
532
-        static::$mime = $mime;
533
-    }
534
-
535
-    /**
536
-     * Get selected MIME type
537
-     */
538
-    public function getMIME()
539
-    {
540
-        return static::$mime;
541
-    }
542
-
543
-    /**
544
-     * Get the selected file extension
545
-     *
546
-     * @return string file extension
547
-     */
548
-    public function getExtension()
549
-    {
550
-        return static::$extension;
551
-    }
552
-
553
-    /**
554
-     * Set the selected file extension
555
-     *
556
-     * @param string $extension file extension
557
-     */
558
-    public function setExtension($extension)
559
-    {
560
-        static::$extension = $extension;
561
-    }
41
+	const BLADE = 'Illuminate\View\View';
42
+	const TWIG = 'Twig\Environment';
43
+	const MUSTACHE = 'Mustache_Engine';
44
+
45
+	public static $mime = 'text/html';
46
+	public static $extension = 'html';
47
+	public static $view;
48
+	public static $errorView = 'debug.php';
49
+	public static $template = 'php';
50
+	public static $handleSession = true;
51
+	public static $convertResponseToArray = false;
52
+
53
+	public static $useSmartViews = true;
54
+	/**
55
+	 * @var null|string defaults to template named folder in Defaults::$cacheDirectory
56
+	 */
57
+	public static $cacheDirectory = null;
58
+	/**
59
+	 * @var array global key value pair to be supplied to the templates. All
60
+	 * keys added here will be available as a variable inside the template
61
+	 */
62
+	public static $data = array();
63
+	/**
64
+	 * @var string set it to the location of your the view files. Defaults to
65
+	 * views folder which is same level as vendor directory.
66
+	 */
67
+	public static $viewPath;
68
+	/**
69
+	 * @var array template and its custom extension key value pair
70
+	 */
71
+	public static $customTemplateExtensions = array('blade' => 'blade.php');
72
+	/**
73
+	 * @var bool used internally for error handling
74
+	 */
75
+	protected static $parseViewMetadata = true;
76
+	/**
77
+	 * @var Restler;
78
+	 */
79
+	public $restler;
80
+
81
+	public function __construct()
82
+	{
83
+		//============ SESSION MANAGEMENT =============//
84
+		if (static::$handleSession) {
85
+			if (session_start() && isset($_SESSION['flash'])) {
86
+				static::$data['flash'] = $_SESSION['flash'];
87
+				unset($_SESSION['flash']);
88
+			}
89
+		}
90
+		if (!static::$viewPath) {
91
+			$array = explode('vendor', __DIR__, 2);
92
+			static::$viewPath = $array[0] . 'views';
93
+		}
94
+	}
95
+
96
+	public function getDependencyMap()
97
+	{
98
+		return array(
99
+			self::BLADE    => 'illuminate/view:^8',
100
+			self::TWIG     => 'twig/twig:^3',
101
+			self::MUSTACHE => 'mustache/mustache:dev-master',
102
+		);
103
+	}
104
+
105
+	public static function blade(array $data, $debug = true)
106
+	{
107
+		$resolver = new EngineResolver();
108
+		$files = new Filesystem();
109
+		$compiler = new BladeCompiler($files, static::$cacheDirectory);
110
+		$engine = new CompilerEngine($compiler);
111
+		$resolver->register('blade', function () use ($engine) {
112
+			return $engine;
113
+		});
114
+		$phpEngine = new PhpEngine($files);
115
+		$resolver->register('php', function () use ($phpEngine) {
116
+			return $phpEngine;
117
+		});
118
+
119
+		/** @var Restler $restler */
120
+		$restler = Scope::get('Restler');
121
+
122
+		//Lets expose shortcuts for our classes
123
+		spl_autoload_register(function ($className) use ($restler) {
124
+			if (isset($restler->apiMethodInfo->metadata['scope'][$className])) {
125
+				return class_alias($restler->apiMethodInfo->metadata['scope'][$className], $className);
126
+			}
127
+			if (isset(Scope::$classAliases[$className])) {
128
+				return class_alias(Scope::$classAliases[$className], $className);
129
+			}
130
+			return false;
131
+		}, true, true);
132
+
133
+		$viewFinder = new FileViewFinder($files, array(static::$viewPath));
134
+		$factory = new Factory($resolver, $viewFinder, new Dispatcher());
135
+		$path = $viewFinder->find(self::$view);
136
+		$view = new View($factory, $engine, self::$view, $path, $data);
137
+		$factory->callCreator($view);
138
+		return $view->render();
139
+	}
140
+
141
+	/**
142
+	 * @param array|object $data
143
+	 * @param bool         $debug
144
+	 *
145
+	 * @return string
146
+	 * @throws \Twig\Error\LoaderError
147
+	 * @throws \Twig\Error\RuntimeError
148
+	 * @throws \Twig\Error\SyntaxError
149
+	 */
150
+	public static function twig($data, $debug = true)
151
+	{
152
+		$loader = new FilesystemLoader(static::$viewPath);
153
+		$twig = new Environment($loader, array(
154
+			'cache'                => is_string(static::$cacheDirectory)
155
+				? static::$cacheDirectory : false,
156
+			'debug'                => $debug,
157
+			'use_strict_variables' => $debug,
158
+		));
159
+		if ($debug) {
160
+			$twig->addExtension(new DebugExtension());
161
+		}
162
+
163
+		$twig->addFunction(
164
+			new TwigFunction(
165
+				'form',
166
+				'Luracast\Restler\UI\Forms::get',
167
+				array('is_safe' => array('html'))
168
+			)
169
+		);
170
+		$twig->addFunction(
171
+			new TwigFunction(
172
+				'form_key',
173
+				'Luracast\Restler\UI\Forms::key'
174
+			)
175
+		);
176
+		$twig->addFunction(
177
+			new TwigFunction(
178
+				'nav',
179
+				'Luracast\Restler\UI\Nav::get'
180
+			)
181
+		);
182
+
183
+		$twig->registerUndefinedFunctionCallback(function ($name) {
184
+			if (
185
+				isset(HtmlFormat::$data[$name]) &&
186
+				is_callable(HtmlFormat::$data[$name])
187
+			) {
188
+				return new TwigFunction(
189
+					$name,
190
+					HtmlFormat::$data[$name]
191
+				);
192
+			}
193
+			return false;
194
+		});
195
+
196
+		$template = $twig->load(static::getViewFile());
197
+		return $template->render((array)$data);
198
+	}
199
+
200
+	/**
201
+	 * @param array|object $data
202
+	 * @param bool         $debug
203
+	 *
204
+	 * @return string
205
+	 */
206
+	public static function handlebar($data, $debug = true)
207
+	{
208
+		return static::mustache($data, $debug);
209
+	}
210
+
211
+	/**
212
+	 * @param array|object $data
213
+	 * @param bool         $debug
214
+	 *
215
+	 * @return string
216
+	 */
217
+	public static function mustache($data, $debug = true)
218
+	{
219
+		$data = (array)$data;
220
+		if (!isset($data['nav'])) {
221
+			$data['nav'] = array_values(Nav::get());
222
+		}
223
+		$options = array(
224
+			'loader'  => new \Mustache_Loader_FilesystemLoader(
225
+				static::$viewPath,
226
+				array('extension' => static::getViewExtension())
227
+			),
228
+			'helpers' => array(
229
+				'form' => function ($text, \Mustache_LambdaHelper $m) {
230
+					$params = explode(',', $m->render($text));
231
+					return call_user_func_array(
232
+						'Luracast\Restler\UI\Forms::get',
233
+						$params
234
+					);
235
+				},
236
+			)
237
+		);
238
+		if (!$debug) {
239
+			$options['cache'] = static::$cacheDirectory;
240
+		}
241
+		$m = new \Mustache_Engine($options);
242
+		return $m->render(static::getViewFile(), $data);
243
+	}
244
+
245
+	/**
246
+	 * @param array|object $data
247
+	 * @param bool         $debug
248
+	 *
249
+	 * @return string
250
+	 * @throws RestException
251
+	 */
252
+	public static function php($data, $debug = true)
253
+	{
254
+		if (static::$view == 'debug') {
255
+			static::$viewPath = dirname(__DIR__) . '/views';
256
+		}
257
+		$view = static::getViewFile(true);
258
+
259
+		if (!is_readable($view)) {
260
+			throw new RestException(
261
+				500,
262
+				"view file `$view` is not readable. " .
263
+				'Check for file presence and file permissions'
264
+			);
265
+		}
266
+
267
+		$path = static::$viewPath . DIRECTORY_SEPARATOR;
268
+		$template = function ($view) use ($data, $path) {
269
+			$data = (array)$data;
270
+			$form = function () {
271
+				return call_user_func_array(
272
+					'Luracast\Restler\UI\Forms::get',
273
+					func_get_args()
274
+				);
275
+			};
276
+			if (!isset($data['form'])) {
277
+				$data['form'] = $form;
278
+			}
279
+			$nav = function () {
280
+				return call_user_func_array(
281
+					'Luracast\Restler\UI\Nav::get',
282
+					func_get_args()
283
+				);
284
+			};
285
+			if (!isset($data['nav'])) {
286
+				$data['nav'] = $nav;
287
+			}
288
+
289
+
290
+			$_ = function () use ($data, $path) {
291
+				extract($data);
292
+				$args = func_get_args();
293
+				$task = array_shift($args);
294
+				switch ($task) {
295
+					case 'require':
296
+					case 'include':
297
+						$file = $path . $args[0];
298
+						if (is_readable($file)) {
299
+							if (
300
+								isset($args[1]) &&
301
+								($arrays = Util::nestedValue($data, $args[1]))
302
+							) {
303
+								$str = '';
304
+								foreach ($arrays as $arr) {
305
+									extract((array)$arr);
306
+									$str .= include $file;
307
+								}
308
+								return $str;
309
+							} else {
310
+								return include $file;
311
+							}
312
+						}
313
+						break;
314
+					case 'if':
315
+						if (count($args) < 2) {
316
+							$args[1] = '';
317
+						}
318
+						if (count($args) < 3) {
319
+							$args[2] = '';
320
+						}
321
+						return $args[0] ? $args[1] : $args[2];
322
+						break;
323
+					default:
324
+						if (isset($data[$task]) && is_callable($data[$task])) {
325
+							return call_user_func_array($data[$task], $args);
326
+						}
327
+				}
328
+				return '';
329
+			};
330
+			extract($data);
331
+			return @include $view;
332
+		};
333
+		$value = $template($view);
334
+		if (is_string($value)) {
335
+			return $value;
336
+		}
337
+	}
338
+
339
+	/**
340
+	 * Encode the given data in the format
341
+	 *
342
+	 * @param array   $data                resulting data that needs to
343
+	 *                                     be encoded in the given format
344
+	 * @param boolean $humanReadable       set to TRUE when restler
345
+	 *                                     is not running in production mode.
346
+	 *                                     Formatter has to make the encoded
347
+	 *                                     output more human readable
348
+	 *
349
+	 * @return string encoded string
350
+	 * @throws \Exception
351
+	 */
352
+	public function encode($data, $humanReadable = false)
353
+	{
354
+		if (!is_readable(static::$viewPath)) {
355
+			throw new \Exception(
356
+				'The views directory `'
357
+				. self::$viewPath . '` should exist with read permission.'
358
+			);
359
+		}
360
+		static::$data['basePath'] = dirname($_SERVER['SCRIPT_NAME']);
361
+		static::$data['baseUrl'] = $this->restler->getBaseUrl();
362
+		static::$data['currentPath'] = $this->restler->url;
363
+
364
+		try {
365
+			$exception = $this->restler->exception;
366
+			$success = is_null($exception);
367
+			$error = $success ? null : $exception->getMessage();
368
+			$data = array(
369
+				'response' => static::$convertResponseToArray
370
+					? Obj::toArray($data)
371
+					: $data,
372
+				'stages'   => $this->restler->getEvents(),
373
+				'success'  => $success,
374
+				'error'    => $error
375
+			);
376
+			$info = $data['api'] = $this->restler->apiMethodInfo;
377
+			$metadata = Util::nestedValue(
378
+				$this->restler, 'apiMethodInfo', 'metadata'
379
+			);
380
+			$view = $success ? 'view' : 'errorView';
381
+			$value = false;
382
+			if (static::$parseViewMetadata && isset($metadata[$view])) {
383
+				if (is_array($metadata[$view])) {
384
+					self::$view = $metadata[$view]['description'];
385
+					$value = Util::nestedValue(
386
+						$metadata[$view], 'properties', 'value'
387
+					);
388
+				} else {
389
+					self::$view = $metadata[$view];
390
+				}
391
+			} elseif (!self::$view) {
392
+				self::$view = static::guessViewName($this->restler->url);
393
+			}
394
+			if (
395
+				isset($metadata['param'])
396
+				&& (!$value || 0 === strpos($value, 'request'))
397
+			) {
398
+				$params = $metadata['param'];
399
+				foreach ($params as $index => &$param) {
400
+					$index = intval($index);
401
+					if (is_numeric($index)) {
402
+						$param['value'] = $this
403
+							->restler
404
+							->apiMethodInfo
405
+							->parameters[$index];
406
+					}
407
+				}
408
+				$data['request']['parameters'] = $params;
409
+			}
410
+			if ($value) {
411
+				$data = Util::nestedValue($data, explode('.', $value));
412
+			}
413
+			if (is_array($data)) {
414
+				$data += static::$data;
415
+			}
416
+			if (false === ($i = strrpos(self::$view, '.'))) {
417
+				$template = self::$template;
418
+			} else {
419
+				self::$template = $template = substr(self::$view, $i + 1);
420
+				self::$view = substr(self::$view, 0, $i);
421
+			}
422
+			if (!static::$cacheDirectory) {
423
+				static::$cacheDirectory = Defaults::$cacheDirectory . DIRECTORY_SEPARATOR . $template;
424
+				if (!file_exists(static::$cacheDirectory)) {
425
+					if (!mkdir(static::$cacheDirectory, 0770, true)) {
426
+						throw new RestException(500,
427
+							'Unable to create cache directory `' . static::$cacheDirectory . '`');
428
+					}
429
+				}
430
+			}
431
+			if (method_exists($class = get_called_class(), $template)) {
432
+				if ($template == 'blade') {
433
+					$this->checkDependency(self::BLADE);
434
+				} elseif ($template == 'twig') {
435
+					$this->checkDependency(self::TWIG);
436
+				} elseif ($template == 'mustache' || $template == 'handlebar') {
437
+					$this->checkDependency(self::MUSTACHE);
438
+				}
439
+				return call_user_func("$class::$template", $data, $humanReadable);
440
+			}
441
+			throw new RestException(500, "Unsupported template system `$template`");
442
+		} catch (Exception $e) {
443
+			static::$parseViewMetadata = false;
444
+			$this->reset();
445
+			throw $e;
446
+		}
447
+	}
448
+
449
+	public static function guessViewName($path)
450
+	{
451
+		if (empty($path)) {
452
+			$path = 'index';
453
+		} elseif (strpos($path, '/')) {
454
+			$path .= '/index';
455
+		}
456
+		$file = static::$viewPath . '/' . $path . '.' . static::getViewExtension();
457
+
458
+		return static::$useSmartViews && is_readable($file)
459
+			? $path
460
+			: static::$errorView;
461
+	}
462
+
463
+	public static function getViewExtension()
464
+	{
465
+		return isset(static::$customTemplateExtensions[static::$template])
466
+			? static::$customTemplateExtensions[static::$template]
467
+			: static::$template;
468
+	}
469
+
470
+	public static function getViewFile($fullPath = false, $includeExtension = true)
471
+	{
472
+		$v = $fullPath ? static::$viewPath . '/' : '';
473
+		$v .= static::$view;
474
+		if ($includeExtension) {
475
+			$v .= '.' . static::getViewExtension();
476
+		}
477
+		return $v;
478
+	}
479
+
480
+	private function reset()
481
+	{
482
+		static::$mime = 'text/html';
483
+		static::$extension = 'html';
484
+		static::$view = 'debug';
485
+		static::$template = 'php';
486
+	}
487
+
488
+	/**
489
+	 * Decode the given data from the format
490
+	 *
491
+	 * @param string $data
492
+	 *            data sent from client to
493
+	 *            the api in the given format.
494
+	 *
495
+	 * @return array associative array of the parsed data
496
+	 *
497
+	 * @throws RestException
498
+	 */
499
+	public function decode($data)
500
+	{
501
+		throw new RestException(500, 'HtmlFormat is write only');
502
+	}
503
+
504
+	/**
505
+	 * @return bool false as HTML format is write only
506
+	 */
507
+	public function isReadable()
508
+	{
509
+		return false;
510
+	}
511
+
512
+	/**
513
+	 * Get MIME type => Extension mappings as an associative array
514
+	 *
515
+	 * @return array list of mime strings for the format
516
+	 * @example array('application/json'=>'json');
517
+	 */
518
+	public function getMIMEMap()
519
+	{
520
+		return array(
521
+			static::$mime => static::$extension
522
+		);
523
+	}
524
+
525
+	/**
526
+	 * Set the selected MIME type
527
+	 *
528
+	 * @param string $mime MIME type
529
+	 */
530
+	public function setMIME($mime)
531
+	{
532
+		static::$mime = $mime;
533
+	}
534
+
535
+	/**
536
+	 * Get selected MIME type
537
+	 */
538
+	public function getMIME()
539
+	{
540
+		return static::$mime;
541
+	}
542
+
543
+	/**
544
+	 * Get the selected file extension
545
+	 *
546
+	 * @return string file extension
547
+	 */
548
+	public function getExtension()
549
+	{
550
+		return static::$extension;
551
+	}
552
+
553
+	/**
554
+	 * Set the selected file extension
555
+	 *
556
+	 * @param string $extension file extension
557
+	 */
558
+	public function setExtension($extension)
559
+	{
560
+		static::$extension = $extension;
561
+	}
562 562
 }
Please login to merge, or discard this patch.
htdocs/includes/restler/framework/Luracast/Restler/Format/YamlFormat.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -18,20 +18,20 @@
 block discarded – undo
18 18
  */
19 19
 class YamlFormat extends DependentFormat
20 20
 {
21
-    const MIME = 'text/plain';
22
-    const EXTENSION = 'yaml';
21
+	const MIME = 'text/plain';
22
+	const EXTENSION = 'yaml';
23 23
 
24
-    const PACKAGE_NAME = 'symfony/yaml:*';
25
-    const EXTERNAL_CLASS = 'Symfony\Component\Yaml\Yaml';
24
+	const PACKAGE_NAME = 'symfony/yaml:*';
25
+	const EXTERNAL_CLASS = 'Symfony\Component\Yaml\Yaml';
26 26
 
27
-    public function encode($data, $humanReadable = false)
28
-    {
29
-        return @Yaml::dump(Obj::toArray($data), $humanReadable ? 10 : 4);
30
-    }
27
+	public function encode($data, $humanReadable = false)
28
+	{
29
+		return @Yaml::dump(Obj::toArray($data), $humanReadable ? 10 : 4);
30
+	}
31 31
 
32
-    public function decode($data)
33
-    {
34
-        return Yaml::parse($data);
35
-    }
32
+	public function decode($data)
33
+	{
34
+		return Yaml::parse($data);
35
+	}
36 36
 }
37 37
 
Please login to merge, or discard this patch.