| Conditions | 13 |
| Paths | 14 |
| Total Lines | 40 |
| Code Lines | 28 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 194 | protected function toJavascript($var) |
||
| 195 | { |
||
| 196 | switch (gettype($var)) { |
||
| 197 | case 'boolean': |
||
| 198 | return $var ? 'true' : 'false'; // Lowercase necessary! |
||
| 199 | case 'integer': |
||
| 200 | case 'double': |
||
| 201 | return (string) $var; |
||
| 202 | case 'resource': |
||
| 203 | case 'string': |
||
| 204 | return '"'.str_replace( |
||
| 205 | ["\r", "\n", "<", ">", "&"], |
||
| 206 | ['\r', '\n', '\x3c', '\x3e', '\x26'], |
||
| 207 | addslashes($var) |
||
|
|
|||
| 208 | ).'"'; |
||
| 209 | break; |
||
| 210 | case 'array': |
||
| 211 | // Arrays in JSON can't be associative. If the array is empty or if it |
||
| 212 | // has sequential whole number keys starting with 0, it's not associative |
||
| 213 | // so we can go ahead and convert it as an array. |
||
| 214 | if (empty($var) || array_keys($var) === range(0, sizeof($var) - 1)) { |
||
| 215 | $output = []; |
||
| 216 | foreach ($var as $v) { |
||
| 217 | $output[] = $this->toJavascript($v); |
||
| 218 | } |
||
| 219 | |||
| 220 | return '[ '.implode(', ', $output).' ]'; |
||
| 221 | } |
||
| 222 | //no break |
||
| 223 | case 'object': |
||
| 224 | // Otherwise, fall through to convert the array as an object. |
||
| 225 | $output = []; |
||
| 226 | foreach ($var as $k => $v) { |
||
| 227 | $output[] = $this->toJavascript(strval($k)).': '.$this->toJavascript($v); |
||
| 228 | } |
||
| 229 | |||
| 230 | return '{ '.implode(', ', $output).' }'; |
||
| 231 | break; |
||
| 232 | default: |
||
| 233 | return 'null'; |
||
| 234 | } |
||
| 237 |