TipitakaContentParaController.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\PaliText;
  4. use App\Services\PaliContentService;
  5. use Illuminate\Http\JsonResponse;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Support\Str;
  8. class TipitakaContentParaController extends Controller
  9. {
  10. /**
  11. * 阅读模式段落内容列表。指定 book 段落区间和 channel
  12. */
  13. public function index(Request $request, PaliContentService $paliService): JsonResponse
  14. {
  15. $data = $request->validate([
  16. 'book' => 'required|integer',
  17. 'para' => 'required|integer',
  18. 'to' => 'integer',
  19. 'channel' => 'required|uuid',
  20. 'format' => 'string|in:html,markdown,react,text',
  21. ]);
  22. $from = $data['para'];
  23. $to = $data['to'] ?? $from;
  24. if ($to < $from) {
  25. return $this->error('invalid paragraph range');
  26. }
  27. $format = $data['format'] ?? 'html';
  28. $items = [];
  29. foreach (range($from, $to) as $para) {
  30. $paragraph = $paliService->readParagraph(
  31. (int) $data['book'],
  32. (int) $para,
  33. $data['channel'],
  34. $this->paraLevel((int) $data['book'], (int) $para),
  35. $format
  36. );
  37. if (empty($paragraph['display'])) {
  38. continue;
  39. }
  40. $items[] = $paragraph;
  41. }
  42. return $this->ok([
  43. 'items' => $items,
  44. 'pagination' => [
  45. 'page' => 1,
  46. 'pageSize' => $to - $from + 1,
  47. 'total' => count($items),
  48. ],
  49. ]);
  50. }
  51. /**
  52. * 单个段落内容。id 格式 {book}-{para}
  53. */
  54. public function show(Request $request, string $id, PaliContentService $paliService): JsonResponse
  55. {
  56. $arrId = explode('-', $id);
  57. if (count($arrId) !== 2 || ! is_numeric($arrId[0]) || ! is_numeric($arrId[1])) {
  58. return $this->error('invalid id');
  59. }
  60. $channel = $request->input('channel');
  61. if (! Str::isUuid($channel)) {
  62. return $this->error('invalid channel');
  63. }
  64. $book = (int) $arrId[0];
  65. $para = (int) $arrId[1];
  66. $paragraph = $paliService->readParagraph(
  67. $book,
  68. $para,
  69. $channel,
  70. $this->paraLevel($book, $para),
  71. $request->input('format', 'html')
  72. );
  73. if (empty($paragraph['display'])) {
  74. return $this->error('no data');
  75. }
  76. return $this->ok($paragraph);
  77. }
  78. /**
  79. * 段落是章节标题时返回标题级别,否则 0
  80. */
  81. protected function paraLevel(int $book, int $para): int
  82. {
  83. $level = PaliText::where('book', $book)
  84. ->where('paragraph', $para)
  85. ->where('level', '<', 8)
  86. ->value('level');
  87. return $level ? (int) $level : 0;
  88. }
  89. }