/node_modules/twig/node_modules/phpjs/functions/var/print_r.js

https://gitlab.com/rickoverman/doo-cli · JavaScript · 76 lines · 61 code · 6 blank · 9 comment · 17 complexity · f33804b3e5ab4d3fa290d7a18219e01a MD5 · raw file

  1. function print_r(array, return_val) {
  2. // discuss at: http://phpjs.org/functions/print_r/
  3. // original by: Michael White (http://getsprink.com)
  4. // improved by: Ben Bryan
  5. // improved by: Brett Zamir (http://brett-zamir.me)
  6. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  7. // input by: Brett Zamir (http://brett-zamir.me)
  8. // depends on: echo
  9. // example 1: print_r(1, true);
  10. // returns 1: 1
  11. var output = '',
  12. pad_char = ' ',
  13. pad_val = 4,
  14. d = this.window.document,
  15. getFuncName = function(fn) {
  16. var name = (/\W*function\s+([\w\$]+)\s*\(/)
  17. .exec(fn);
  18. if (!name) {
  19. return '(Anonymous)';
  20. }
  21. return name[1];
  22. };
  23. repeat_char = function(len, pad_char) {
  24. var str = '';
  25. for (var i = 0; i < len; i++) {
  26. str += pad_char;
  27. }
  28. return str;
  29. };
  30. formatArray = function(obj, cur_depth, pad_val, pad_char) {
  31. if (cur_depth > 0) {
  32. cur_depth++;
  33. }
  34. var base_pad = repeat_char(pad_val * cur_depth, pad_char);
  35. var thick_pad = repeat_char(pad_val * (cur_depth + 1), pad_char);
  36. var str = '';
  37. if (typeof obj === 'object' && obj !== null && obj.constructor && getFuncName(obj.constructor) !==
  38. 'PHPJS_Resource') {
  39. str += 'Array\n' + base_pad + '(\n';
  40. for (var key in obj) {
  41. if (Object.prototype.toString.call(obj[key]) === '[object Array]') {
  42. str += thick_pad + '[' + key + '] => ' + formatArray(obj[key], cur_depth + 1, pad_val, pad_char);
  43. } else {
  44. str += thick_pad + '[' + key + '] => ' + obj[key] + '\n';
  45. }
  46. }
  47. str += base_pad + ')\n';
  48. } else if (obj === null || obj === undefined) {
  49. str = '';
  50. } else { // for our "resource" class
  51. str = obj.toString();
  52. }
  53. return str;
  54. };
  55. output = formatArray(array, 0, pad_val, pad_char);
  56. if (return_val !== true) {
  57. if (d.body) {
  58. this.echo(output);
  59. } else {
  60. try {
  61. d = XULDocument; // We're in XUL, so appending as plain text won't work; trigger an error out of XUL
  62. this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">' + output + '</pre>');
  63. } catch (e) {
  64. this.echo(output); // Outputting as plain text may work in some plain XML
  65. }
  66. }
  67. return true;
  68. }
  69. return output;
  70. }