Code.php 2.4 KB

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