Code.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. <?php
  2. namespace Dcat\Admin\Widgets;
  3. use Illuminate\Contracts\Support\Renderable;
  4. class Code extends Markdown
  5. {
  6. /**
  7. * @var string
  8. */
  9. protected $lang = 'php';
  10. /**
  11. * @param string $content
  12. * @param int $start
  13. * @param int $end
  14. */
  15. public function __construct($content = '', int $start = 1, int $end = 10)
  16. {
  17. if (is_file($content)) {
  18. $this->read($content, $start, $end);
  19. $content = '';
  20. }
  21. parent::__construct($content);
  22. }
  23. /**
  24. * 设置语言
  25. *
  26. * @param string $lang
  27. *
  28. * @return $this
  29. */
  30. public function lang(string $lang)
  31. {
  32. $this->lang = $lang;
  33. return $this;
  34. }
  35. public function javascript()
  36. {
  37. $this->lang = 'javascript';
  38. return $this;
  39. }
  40. public function html()
  41. {
  42. $this->lang = 'html';
  43. return $this;
  44. }
  45. public function java()
  46. {
  47. $this->lang = 'java';
  48. return $this;
  49. }
  50. public function python()
  51. {
  52. $this->lang = 'python';
  53. return $this;
  54. }
  55. /**
  56. * 读取指定行上下区间文件内容.
  57. *
  58. * @param string $file
  59. * @param int $lineNumber
  60. * @param int $padding
  61. *
  62. * @return $this
  63. */
  64. public function padding($file, $lineNumber = 1, $padding = 5)
  65. {
  66. return $this->read($file, $lineNumber - $padding, $lineNumber + $padding);
  67. }
  68. /**
  69. * 读取指定行文件内容.
  70. *
  71. * @param string $file
  72. * @param int $start
  73. * @param int $end
  74. *
  75. * @return $this
  76. */
  77. public function read($file, $start = 1, $end = 10)
  78. {
  79. if (! $file or ! is_readable($file) || $end < $start) {
  80. return $this;
  81. }
  82. $file = fopen($file, 'r');
  83. $line = 0;
  84. $source = '';
  85. while (($row = fgets($file)) !== false) {
  86. if (++$line > $end) {
  87. break;
  88. }
  89. if ($line >= $start) {
  90. $source .= htmlspecialchars($row, ENT_NOQUOTES, config('charset', 'utf-8'));
  91. }
  92. }
  93. fclose($file);
  94. return $this->content($source);
  95. }
  96. protected function build()
  97. {
  98. if ($this->content instanceof Renderable) {
  99. $this->content = $this->content->render();
  100. }
  101. return <<<EOF
  102. <div {$this->formatHtmlAttributes()}><textarea style="display:none;">
  103. ```{$this->lang}
  104. {$this->content}
  105. ```
  106. </textarea></div>
  107. EOF;
  108. }
  109. }