Markdown.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace App\Tools;
  3. use Illuminate\Support\Str;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Facades\Http;
  6. class Markdown
  7. {
  8. public static function driver($driver)
  9. {
  10. $GLOBALS['markdown.driver'] = $driver;
  11. }
  12. public static function render($text)
  13. {
  14. if (
  15. isset($GLOBALS['markdown.driver']) &&
  16. $GLOBALS['markdown.driver'] === 'str'
  17. ) {
  18. return Markdown::strdown($text);
  19. } else {
  20. return Markdown::strdown($text);
  21. }
  22. }
  23. public static function morus_restful($text)
  24. {
  25. $host = config('mint.server.rpc.morus.host');
  26. Log::debug('morus host=' . $host);
  27. $response = Http::post($host, [
  28. 'text' => $text
  29. ]);
  30. if ($response->successful()) {
  31. return $response->json('data');
  32. } else {
  33. Log::error('morus_restful fail markdown=' . $text);
  34. return Str::markdown($text);
  35. }
  36. }
  37. public static function morus($text)
  38. {
  39. if (isset($GLOBALS['morus_client'])) {
  40. $client = $GLOBALS['morus_client'];
  41. } else {
  42. $host = config('mint.server.rpc.morus.host') . ':' . config('mint.server.rpc.morus.port');
  43. Log::debug('morus host=' . $host);
  44. $client = new \Mint\Morus\V1\MarkdownClient($host, [
  45. 'credentials' => \Grpc\ChannelCredentials::createInsecure(),
  46. ]);
  47. $GLOBALS['morus_client'] = $client;
  48. }
  49. $request = new \Mint\Morus\V1\MarkdownToHtmlRequest();
  50. $request->setPayload($text);
  51. $request->setSanitize(true);
  52. list($response, $status) = $client->ToHtml($request)->wait();
  53. if ($status->code !== \Grpc\STATUS_OK) {
  54. Log::error("ERROR: " . $status->code . ", " . $status->details);
  55. return Str::markdown($text);
  56. }
  57. return $response->getPayload();
  58. }
  59. public static function strdown($text)
  60. {
  61. $text = str_replace("** ", "**\r\n ", $text);
  62. $html = Str::markdown($text);
  63. $html = self::replaceSinglePWithSpan($html);
  64. return $html;
  65. }
  66. /**
  67. * 如果字符串中只有一对 p 标签,则替换为 span
  68. *
  69. * @param string $html
  70. * @return string
  71. */
  72. public static function replaceSinglePWithSpan(string $html): string
  73. {
  74. preg_match_all('/<p\b[^>]*>.*?<\/p>/is', $html, $matches);
  75. if (count($matches[0]) === 1) {
  76. return preg_replace(
  77. ['/^\s*<p\b([^>]*)>/i', '/<\/p>\s*$/i'],
  78. ['<span$1>', '</span>'],
  79. $html
  80. );
  81. }
  82. return $html;
  83. }
  84. }