Dump.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace Dcat\Admin\Widgets;
  3. use Illuminate\Contracts\Support\Renderable;
  4. class Dump extends Widget
  5. {
  6. /**
  7. * @var string
  8. */
  9. protected $view = 'admin::widgets.dump';
  10. /**
  11. * @var string
  12. */
  13. protected $padding = '10px';
  14. /**
  15. * @var string
  16. */
  17. protected $content = '';
  18. protected $maxWidth;
  19. /**
  20. * Dump constructor.
  21. *
  22. * @param array|object|string $content
  23. * @param string|null $padding
  24. */
  25. public function __construct($content, string $padding = null)
  26. {
  27. $this->content($content);
  28. $this->padding($padding);
  29. }
  30. public function content($content)
  31. {
  32. $content = $this->convertJsonToArray($content) ?: $content;
  33. if ($content instanceof Renderable) {
  34. $this->content = $content->render();
  35. } elseif (is_array($content) || is_object($content)) {
  36. $this->content = json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  37. } else {
  38. $this->content = $content;
  39. }
  40. return $this;
  41. }
  42. /**
  43. * @param string|null $padding
  44. *
  45. * @return $this
  46. */
  47. public function padding(?string $padding)
  48. {
  49. if ($padding) {
  50. $this->padding = $padding;
  51. }
  52. return $this;
  53. }
  54. /**
  55. * @param string $width
  56. *
  57. * @return $this
  58. */
  59. public function maxWidth($width)
  60. {
  61. $this->maxWidth = $width;
  62. return $this;
  63. }
  64. /**
  65. * @param mixed $content
  66. *
  67. * @return array|null
  68. */
  69. protected function convertJsonToArray($content)
  70. {
  71. if (
  72. is_string($content) &&
  73. (
  74. (strpos($content, '{') === 0 && strpos($content, '}', -1) !== false) ||
  75. (strpos($content, '[') === 0 && strpos($content, ']', -1) !== false)
  76. )
  77. ) {
  78. return json_decode($content, true);
  79. }
  80. }
  81. public function render()
  82. {
  83. $this->defaultHtmlAttribute(
  84. 'style',
  85. 'white-space:pre-wrap;'.($this->maxWidth ? "max-width:{$this->maxWidth};" : '')
  86. );
  87. return <<<EOF
  88. <div style="padding:{$this->padding}"><pre class="dump" {$this->formatHtmlAttributes()}>{$this->content}</pre></div>
  89. EOF;
  90. }
  91. }