TipitakaContentParaController.php 2.4 KB

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